到目前为止,接近回答问题的唯一链接是: 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 :(得分: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;
}
未经测试的代码。