在 C++ 中的 class 中定义固定大小的向量?

Defining a vector with fixed size inside a class in c++?

以下是我的 C++ 代码部分

class Myclass 
{
    public:
       vector< vector<int> >edg(51); // <--- This line gives error
       // My methods go here
};

注释中标记的行给我错误:
expected identifier before numeric constant
expected ‘,’ or ‘...’ before numeric constant

但是当我执行以下操作时它编译没有错误

  vector< vector<int> >edg(51); // Declaring globally worked fine
  class Myclass 
  {
    public:
       // My methods go here
  };

我发现即使我只是在第一种方法中定义 vector < vector<int> >edg 它工作正常,所以问题出在常量大小 51 上,我似乎不明白。我尝试谷歌搜索,但由于我的 oop 概念很薄弱,我不太了解,谁能解释为什么会这样?

这是一个限制。定义 class 个成员。如果您想要一个固定大小的向量,只需使用 std::array 即可,这样您就可以做到这一点。

class Myclass 
{
    public:
       array< vector<int>, 51 >edg; 
};

或者,您可以在构造函数中声明大小:

class Myclass 
{
    public:
       vector< vector<int> >edg; 
       Myclass() : edg(51) {}
};

In-class 初始化只能用 = 或括号列表完成,不能用 ()。由于 vector 与括号列表的行为不同,因此您需要使用 =.

vector< vector<int> > edg = vector< vector<int> >(51);

或者以老式的方式在构造函数中初始化它。

MyClass() : edg(51) {}