I have a class called Cal and it's .cpp and .h counterpart
Headerfile has
class Cal {
private:
int wa[2][2];
public:
void do_cal();
};
.cpp file has
#include "Cal.h"
void Cal::do_cal() {
print(wa) // where print just itterates and prints the elements in wa
}
My question is how do I initialize the array wa
? I just can't seem to get it to work.
I tried with :
int wa[2][2] = {
{5,2},
{7,9}
};
in the header file but I get errors saying I cant do so as it's against iso..something.
Tried also to initialize the array wa
in the constructor but that didnt work either.. What am I missing ?
Thanks
If it can be static, you can initialize it in your .cpp file. Add the static keyword in the class declaration:
class Cal {
private:
static int wa[2][2];
public:
void do_cal();
};
and at file scope 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 would work well (along with making it const). You only get one that's shared with each instance of your class though.
You cannot initialize array elements in a class declaration. I recently tried to find a way to do just that. From what I learned, you have to do it 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's possible (and probable) that there's a much better way to do this, but from my research last week, this is how to do it with a multi dimensional array. I'm interested if anyone has a better method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With