use*_*248 1 c++ arrays size header declaration
我不确定如何提出这个问题所以我将从一些示例代码开始:
//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*/
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码有效吗?更具体地说,我可以将我的头文件中的字符串数组大小为x,即使在创建A对象之前x没有特别赋值吗?
如果这不起作用,我唯一的另一种选择是使用动态分配的数组吗?
代码无效.你应该使用矢量.
class A
{
public:
A();
private:
int x;
std::vector<std::string> arr;
};
A::A () : x(command_gets_x()), arr(x) {}
Run Code Online (Sandbox Code Playgroud)
由于arr值是由值初始化的x,因此构造函数仅在x前置arr时A(在您的定义中)才有效.但是,如果唯一的目的x是跟踪数组的大小,则没有必要,因为a vector具有该size()方法.
class A
{
public:
A() : arr(command_gets_x()) {}
int x () const { return arr.size(); }
//...
private:
std::vector<std::string> arr;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
959 次 |
| 最近记录: |