我不太确定如何提出这个问题,所以我将从一些示例代码开始:
//header file
class A
{
public:
A();
private:
int x;
std::string arr[x];
}
//cpp file
class A
{
public:
A()
{
/*code to get the value of x from a cmd call*/
}
}
此代码有效吗?更具体地说,我是否可以让我的头文件中的字符串数组的大小为 x,即使在创建 A 对象之前没有专门为 x 指定值?
如果这不起作用,我唯一的选择是使用动态分配的数组吗?
最佳答案
代码无效。您应该改用 vector 。
class A
{
public:
A();
private:
int x;
std::vector<std::string> arr;
};
A::A () : x(command_gets_x()), arr(x) {}
由于 arr
是由 x
的值初始化的,因此构造函数仅在 x
在 arr
之前工作在 A
中(因为它在您的定义中)。但是,如果 x
的唯一目的是跟踪数组的大小,则没有必要,因为 vector
具有 size()
方法。
class A
{
public:
A() : arr(command_gets_x()) {}
int x () const { return arr.size(); }
//...
private:
std::vector<std::string> arr;
};
关于c++ - 数组声明和大小初始化(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11750347/