我正在尝试创建一个这样的类:
class CLASS
{
public:
//stuff
private:
int x, y;
char array[x][y];
};
当然,直到我将
int x, y;
更改为const static int x = 10, y = 10;
这是不切实际的,因为我正在尝试从文件中读取x和y的值。那么,有什么方法可以使用非常量值初始化数组,或者声明数组并在不同的语句中声明其大小?而且我知道这可能需要创建一个数组类,但是我不确定从哪里开始,并且当数组本身不是动态的时,我不想创建一个二维动态列表,只是大小是在编译时未知。
最佳答案
编译器在编译时需要具有该类的确切大小,您将必须使用new运算符动态分配内存。
切换char数组[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;
};
*编辑:
我有复制构造函数
和赋值运算符
关于c++ - 有没有一种方法可以使用非常量变量初始化数组? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23753028/