在结构中声明向量时,C++ 不是类型错误

C++ not a type error when declaring a vector in a struct

我希望有一个包含向量的节点数据结构。我事先知道向量的大小,因此我用 const 说明符预先初始化了一个 SIZE 变量。

代码 (vectorTest.cpp):

#include <vector>

const int SIZE = 100;

struct node {
  std::vector<int> myVec(SIZE); // ERROR: 'SIZE' is not a type
};

int main(int argc, char const *argv[]) {
  std::vector<int> myVec(SIZE); // VALID
  return 0;
}

编译(g++ 5.4.0):

g++ -std=c++1y vectorTest.cpp -o vectorTest

里面main(),一切都很好,我可以高兴地宣布: std::vector<int> A(SIZE);。但是,当我尝试在 struct 中定义相同内容时,我收到一条错误消息,指出 'SIZE' is not a type.

我知道我可以这样做来使用 C 风格的数组定义来声明一个 int 的向量,

struct other_node {
  int myVec[SIZE]; // VALID
};

但我想知道为什么 std::vector 无法做到这一点。

问题:

What does this error mean?

编译器需要行中的函数声明。因此,它需要一个类型而不是一个值。

Why can I not declare a vector of predefined size inside a struct?

您可以使用:

// Legal but it initializes myVector with one element whose value is SIZE.
// std::vector<int> myVec{SIZE};
std::vector<int> myVec = std::vector<int>(SIZE);

编译器不期望在类型定义中的那个点进行初始化(它是 struct 并不重要,可以是 classunion,也)。唯一有效的是成员函数的声明,其结构为 <returntype> <name>(<arguments...>)。对于参数,您可以省略名称而只提供类型。在本例中,它是 SIZE,但由于这不是类型,因此您会收到错误消息。

工作备选方案:

  • 声明构造函数并在那里初始化向量。
  • 使用所需大小的向量进行初始化:vector<int> myVec = vector<int>(SIZE);

备注:

  • 一个类似的错误称为 "most vexing parse of C++"。
  • 使用 ALL_UPPERCASE 应始终且仅用于宏。这个约定可以帮助你发现他们,就像是对他们不同行为的警告。