有没有办法用非常量变量初始化数组?(C++)

11 c++ arrays

我正在尝试创建一个类:

class CLASS
{
public:
    //stuff
private:
    int x, y;
    char array[x][y];
};
Run Code Online (Sandbox Code Playgroud)

当然,直到我换int x, y;到它才行

const static int x = 10, y = 10;
Run Code Online (Sandbox Code Playgroud)

这是不切实际的,因为我试图从文件中读取x和y的值.那么有没有办法初始化一个具有非常量值的数组,或者声明一个数组并在不同的语句中声明它的大小?我知道这可能需要创建一个数组类,但是我不知道从哪里开始,我不想在数组本身不是动态的时候创建一个2D动态列表,只是大小是在编译时不知道.

Aar*_*ron 15

使用矢量.

#include <vector>
class YourClass
{
public:
    YourClass()
    : x(read_x_from_file()), y(read_y_from_file())
    {
        my_array.resize(x);
        for(int ix = 0; ix < x; ++ix)
            my_array[ix].resize(y);
    }

    //stuff

private:
    int x, y;
    std::vector<std::vector<char> > my_array;
};
Run Code Online (Sandbox Code Playgroud)


Ste*_*ury 10

编译时编译器需要具有类的确切大小,您必须使用new运算符来动态分配内存.

切换字符数组[x] [y]; 到char**数组; 并在构造函数中初始化您的数组,并且不要忘记在析构函数中删除您的数组.

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<x ; ++i )
            for( int j=0 ; j<x ; ++j )
                array[i][j] = otherClass.array[i][j];
    }

    ~MyClass(){
        deleteMe();
    }

    void allocate( int x, int y){
        array = new char*[x];
        for( int i = 0; i < y; i++ )
            array[i] = new char[y];
    }

    void deleteMe(){
        for (int i = 0; i < y; i++)
           delete[] array[i];
        delete[] array;
    }

    MyClass& operator= (const MyClass& otherClass)
    {
        if( this != &otherClass )
        {
            deleteMe();
            x = otherClass.x;
            y = otherClass.y;
            allocate(x, y);
            for( int i=0 ; i<x ; ++i )
                for( int j=0 ; j<y ; ++j )
                    array[i][j] = otherClass.array[i][j];            
        }
        return *this;
    }
private:
    int x, y;
    char** array;
};
Run Code Online (Sandbox Code Playgroud)

*编辑:我有复制构造函数和赋值运算符

  • 那很糟.复制结构怎么样?分配操作员.为什么不将所有内存都放在一个连续的块中而不是一个数组中.那么构造函数中的异常处理呢. (4认同)