2013-04-27 75 views
0

到目前为止,这是接近回答这个问题的唯一联系是这样的初始化对象的2D矢量: How do I initialize a stl vector of objects who themselves have non-trivial constructors?如何真正从类/构造

不过,我试图做到这一点,我仍然难住它。

相关的代码:

边缘

// 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文件分开的代码

+0

您链接的问题在普通问题中有答案。 – chris 2013-04-27 22:05:28

回答

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; 
} 

未经测试的代码。

+5

我建议使其他变量也是初始化列表的一部分。这真的是它应该的方式。 – pmr 2013-04-27 22:12:29

+0

@john 非常感谢您,当您必须初始化私有字段时,似乎初始化程序列表被视为最佳选项 – JBRPG 2013-04-27 22:58:44