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

C++ vector as class member vs in function

当我在函数中使用 vector 时,我得到了一个变量 D 并且它起作用了。

 vector<int> D(100);

然而,当我决定将它用作 class 成员时,我收到以下奇怪的错误:

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

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

member variable 的默认成员初始化器 (C++11 起) 仅支持等号初始化器(和大括号初始化器,与此用例不匹配)。

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

你可以

vector<int> D = vector<int>(100);

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

struct x {
    vector<int> D;
    x() : D(100) {}
};