Initializing a private C / C ++ array in the header file

I have a Cal class and its .cpp and .h counter

Header file has

class Cal { private: int wa[2][2]; public: void do_cal(); }; 

.cpp has

 #include "Cal.h" void Cal::do_cal() { print(wa) // where print just itterates and prints the elements in wa } 

My question is how to initialize a wa array? I just can't get it to work.

I tried:

 int wa[2][2] = { {5,2}, {7,9} }; 

in the header file, but I get errors saying that I cannot do this because it is against iso..something.

I also tried to initialize the wa array in the constructor, but that didn't work either. What am I missing?

thanks

+4
source share
3 answers

If it can be static, you can initialize it in your .cpp file. Add the static keyword to the class declaration:

 class Cal { private: static int wa[2][2]; public: void do_cal(); }; 

and in the file area in the .cpp file add:

 #include "Cal.h" int Cal::wa[2][2] = { {5,2}, {7,9} }; void Cal::do_cal() { print(wa) // where print just itterates and prints the elements in wa } 

If you never change it, this will work well (along with creating a const). However, you only get one that is shared with every instance of your class.

+10
source

You cannot initialize array elements in a class declaration. I recently tried to find a way to do just that. From what I found out, you should do this in your initialize function, one element at a time.

 Cal::Cal{ wa[0][0] = 5; wa[0][1] = 2; wa[1][0] = 7; wa[1][1] = 9; } 

It is possible (and likely) that there is a much better way to do this, but from my research last week, this is how to do it using a multidimensional array. I am wondering if anyone has a better method.

+7
source

You cannot do it easily. If you do not want to specify each element separately, as in Perchik's answer , you can create one static array and memcpy , which (probably will be faster for non-trivial array sizes):

 namespace { const int default_wa[2][2] = {{5, 2}, {7, 9}}; } Cal::Cal { memcpy(&wa[0][0], &default_wa[0][0], sizeof(wa)); } 
+5
source

All Articles