在模板化 class 中初始化私有成员变量向量

Initializing private member variable vector in a templated class

我目前正在研究一个模板图 class,它利用两个向量来创建邻接矩阵。我可以让它在模板之外工作 class,但我似乎无法初始化向量。

这是我的资料:

#include <stdexcept>
#include <vector>
#include <list>
#include <string>

using namespace std;

namespace GraphNameSpace
{
  template <class T>
  class Graph
  {
  private:
    vector<int> colOfRow(100);
    vector<vector<int> > matrix(100);
  };
}

我收到:

错误:数字常量之前需要标识符

错误:数字常量前需要“,”或“...”

那些无法在模板中初始化的原因是什么 class,解决方案是什么? 我知道这可能不是最有效的方式,但这是我最了解的方式。如果您考虑另一种更好的方法,您能否提供您将采用的方法?

与模板无关class。您可以使用 member initializer list 来初始化成员变量:

namespace GraphNameSpace
{
  template <class T>
  class Graph
  {
  private:
    vector<int> colOfRow;
    vector<vector<int> > matrix;
  public:
    Graph() : colOfRow(100), matrix(100) {}
  };
}

default member initializer(自c++11起):

namespace GraphNameSpace
{
  template <class T>
  class Graph
  {
  private:
    vector<int> colOfRow{100};
    vector<vector<int> > matrix{100};
  };
}