Is there a way to initialize an array with non-constant variables? (C++)

后端 未结 9 2115
無奈伤痛
無奈伤痛 2020-12-06 11:20

I am trying to create a class as such:

class CLASS
{
public:
    //stuff
private:
    int x, y;
    char array[x][y];
};

Of course, it does

9条回答
  •  执笔经年
    2020-12-06 12:07

    The compiler need to have the exact size of the class when compiling, you will have to use the new operator to dynamically allocate memory.

    Switch char array[x][y]; to char** array; and initialize your array in the constructor, and don't forget to delete your array in the destructor.

    class MyClass
    {
    public:
        MyClass() {
            x = 10; //read from file
            y = 10; //read from file
            allocate(x, y);
        }
    
        MyClass( const MyClass& otherClass ) {
            x = otherClass.x;
            y = otherClass.y;
            allocate(x, y);
    
            // This can be replace by a memcopy
            for( int i=0 ; i

    *EDIT: I've had the copy constructor and the assignment operator

提交回复
热议问题