C/C++ private array initialization in the header file

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

Answers


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.


You can't do it easily. If you don't want to specify each element individually like in Perchik's answer, you can create one static array and memcpy that (which will probably 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));
}

Need Your Help

How to get format numbers with decimals (XCode)

iphone xcode decimal number-formatting

My objective is to create a customer calculator application for iPhone and I am using Xcode to write my application. My problem, that I cannot find a solution for, is how to format a number that uses

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.