Why am I getting an error when declaring a variabl

2019-07-07 03:19发布

问题:

I'm trying to make a class that has a simple integer with in it. Of course, it uses header files and whatnot.

Here's the code:

class.h

 class consolBuf
{
private:
    int buffersize1 = 10; //Data member initializer is not allowed
    int buffersize2 = 10;
    static char screenBuffer[10][10]; //screenBuffer
public:
    consolBuf(void);
    ~consolBuf(void);
    void draw();
    void write(int x, int y);
    char get(int x, int y);
};

For some reason some reson Visual Studio keeps complaining that I can't declare a integer in the class.h. I've searched everywhere and I can't find an answer. Is there something I'm missing?

回答1:

Indeed you can't initialize members like that. If you wanted to initialize those as default values for each instance, you would do that in the constructor:

consolBuf::consolBuf()
    : buffersize1(10)
    , buffersize2(10)
{

}


回答2:

In C++03, only static constant values can be defined inside the class. But then, it seems that this is what you need anyway in your case:

class consolBuf
{
private:
    static int const buffersize1 = 10; //Data member initializer is now allowed
    static int const buffersize2 = 10;
    static char screenBuffer[buffersize1][buffersize2]; //screenBuffer
public:
    consolBuf(void);
    ~consolBuf(void);
    void draw();
    void write(int x, int y);
    char get(int x, int y);
};

Note that in C++11, your original code is allowed. So if your original code is really what you wanted, all you might have to do is to enable C++11 features. In C++03, you'll have to use member inizializers in the constructor instead.



回答3:

If you want to initialize fixed values, declare buffersize1 and buffersize2 as being static const. Otherwise if you want the variables to be local to each instance of a class, initialize them in the constructor.

Apparently C++0x/C++11 allows your above code, however I'd personally still prefer instance variables to be initialized all together in a constructor.