In class table

Hi I would need one static table to be accessible from three methods.
I do know the values at the time of writting code.

How can I define global table with values in class?

I tried:
int tab[] = { 1, 2, 3, 4, 5 ,6, 7, 8, 9, 10};
but it only works if I define it outside of class, so - globally.

I read about it is bad thing to have global table. Why?
Last edited on
closed account (zwA4jE8b)
1
2
3
4
5
6
7
8
class table
{
   int tab[] = { 1, 2, 3, 4, 5 ,6, 7, 8, 9, 10};
public:
   func1();
   func2();
   func3();
};


all three functions will have access to 'tab'
If you know the size but not the values then just declare the size of tab, you can write in the values later.
If you do not know the size then you need to use a std::vector or a dynamic array.
Hi, I have tried:
1
2
3
4
5
public:
func();
func2();
private:
float tab[]  = { (float)0.5, 1,(float)1.5, 2, (float)2.5, 3 };


but I get error:

error C2059: syntax error : '{'
error C2334: unexpected token(s) preceding '{'; skipping apparent function body
closed account (zwA4jE8b)
whats the rest of the class or struct look like?
closed account (zwA4jE8b)
Sorry, I forgot that you can not initialize variables in the class declaration.

You can give it a size int tab[10]; that way you have an integer array named tab that is size 10
closed account (zwA4jE8b)
you will have to initialize it in either the ctor, or write a method to either init it or get values
Or:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

class Foo
{
public:
	Foo() {}
	void Func0() { std::cout << "table[0] = " << table[0] << std::endl; }
	void Func1() { std::cout << "table[1] = " << table[1] << std::endl; }
	void Func2() { std::cout << "table[2] = " << table[2] << std::endl; }
	void Func3() { std::cout << "table[3] = " << table[3] << std::endl; }
private:
	static const float table [];
};

const float Foo::table[] = { 0.25f, 0.4f, 0.023f, 1.24f };

int main()
{
    Foo f;
    f.Func0();

    std::cout << "Press enter to exit...";
    std::cin.get();
    return 0;
}
I tried with
int tab[10]; and than enter the values in initialize function.
I get the following error:
 error LNK2001: unresolved external symbol
.

What if I declare table outside the class - globally. Why would this not be good?
Topic archived. No new replies allowed.