数组声明和大小初始化(C++)

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没有特别赋值吗?

如果这不起作用,我唯一的另一种选择是使用动态分配的数组吗?

jxh*_*jxh 5

代码无效.你应该使用矢量.

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前置arrA(在您的定义中)才有效.但是,如果唯一的目的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)

  • 或许注意到这只适用于在类中的`arr`之前声明`x`时?或者当我们有'arr.size()`时我们不需要`x`. (3认同)
  • @user1553248:`std::vector&lt;std::vector&lt;std::string&gt; &gt; arr(command_get_x(),std::vector&lt;std::string&gt;(6));` (2认同)