我想知道是否可以声明一个数组(此时大小未知)作为类的私有(private)成员,然后在类的构造函数中设置大小。例如:
class Test {
int a[];
public:
Test(int size);
};
Test::Test(int size) {
a[size]; // this is wrong, but what can i do here?
}
这是可能的还是我应该使用动态数组?谢谢!
最佳答案
简短回答:否(数组的大小仅在编译时定义)
长答案:
您可以使用 vector 来获得相同的结果:
class Test
{
std::vector<int> a;
public:
Test(std::size_t size):
a(size)
{}
};
关于 header 中的c++数组声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/322086/