0

到目前为止,接近回答这个问题的唯一链接是: 如何初始化自己具有非平凡构造函数的对象的 stl 向量?

但是,我试图这样做,但我仍然很难过。

相关代码:

边缘

// Edge Class
class Edge{
  public:
    // std::string is used to avoid not a name type error
    Edge (std::string, double);
    double get_dist();
    std::string get_color();
    ~Edge();
  private:
    std::string prv_color; // prv_ tags to indicate private
    double prv_distance;
};

Edge::Edge (std::string color, double distance){
  prv_color = color;
  prv_distance = distance;
};

图形

// Graph Class

class Graph{
  public:
    Graph (double, double);
    double get_dist_range();
    ~Graph();

  private:
    double prv_edge_density; // how many edges connected per node
    double prv_dist_range; // start from 0 to max distance
    std::vector < std::vector <Edge*> > nodes; // the proper set-up of 
};

// Graph constructor
Graph::Graph (double density, double max_distance){
  prv_edge_density = density;
  prv_dist_range = max_distance;
  nodes (50, std::vector <Edge*> (50)); // THIS LINE STUMPS ME MOST
};

当我试图初始化一个对象指针向量时,我从以下行中得到了这个错误:

nodes (50, std::vector <Edge*> (50)); // Error at this line

error: no match for call to ‘(std::vector<std::vector<Edge*, std::allocator<Edge*> >,
  std::allocator<std::vector<Edge*, std::allocator<Edge*> > > >)
  (int, std::vector<Edge*, std::allocator<Edge*> >)’

我想尽快得到这方面的建议。

注意:假设我已经使用 .cpp 文件和 .h 文件来分隔代码

4

1 回答 1

4

你需要了解初始化列表

// Graph constructor
Graph::Graph (double density, double max_distance) :
  nodes (50, std::vector <Edge*> (50))
{
  prv_edge_density = density;
  prv_dist_range = max_distance;
}

未经测试的代码。

于 2013-04-27T22:08:22.953 回答