C++ 向量作为类成员与函数

Adi*_*ore 2 c++ syntax templates

当我vector在函数中使用如下时,我得到一个变量 D 并且它可以工作。

 vector<int> D(100);
Run Code Online (Sandbox Code Playgroud)

但是,当我决定将其用作类成员时,出现以下奇怪的错误:

error: expected identifier before numeric constant
   99 |     vector<int> D(100);
      |                   ^~~
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么会出现这个特定错误吗?我可以在类中使用数组作为int D[100].

son*_*yao 5

成员变量的默认成员初始值设定项(C++11 起)仅支持等号初始值设定项(和花括号初始值设定项,与此用例不匹配)。

通过默认成员初始值设定项,它是包含在成员声明中的大括号或等号初始值设定项,并且在构造函数的成员初始值设定项列表中省略该成员时使用。

你可以

vector<int> D = vector<int>(100);
Run Code Online (Sandbox Code Playgroud)

或者使用成员初始化列表。例如

struct x {
    vector<int> D;
    x() : D(100) {}
};
Run Code Online (Sandbox Code Playgroud)