有没有一种方法来初始化与非恒定的数组变量? (C ++) [英] Is there a way to initialize an array with non-constant variables? (C++)
问题描述
我想创建一个类,例如:
I am trying to create a class as such:
class CLASS
{
public:
//stuff
private:
int x, y;
char array[x][y];
};
当然,这是行不通的,直到我换 INT X,Y;
到
const static int x = 10, y = 10;
这是不现实的,因为我想从文件中读取x和y的值。那么,有没有办法与非contant值初始化数组或声明数组,并在不同的语句声明它的大小?我知道这可能需要一个数组类的创作,但我不知道从哪里开始就这一点,我并不想创建一个二维动态列表时,数组本身不是动态的,只是大小在编译时不知道的。
Which is impractical, because I am trying to read the values of x and y from a file. So is there any way to initialize an array with non-contant values, or declare an array and declare its size on different statements? And I know this would probably require the creation of an array class, but I'm not sure where to start on this, and I don't want to create a 2D dynamic list when the array itself is not dynamic, just the size is not known at compile-time.
推荐答案
编译器需要有一流的确切大小编译时,你将不得不使用new操作符来动态分配内存。
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.
切换字符数组[X] [Y]为char **数组;和初始化在构造函数中的数组,并且不要忘记删除数组在析构函数。
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<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;
};
*编辑:
我已经拷贝构造函数
并赋值运算符
* I've had the copy constructor and the assignment operator
这篇关于有没有一种方法来初始化与非恒定的数组变量? (C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!