我试图在c ++中实现图形。我有一个节点类,其中包含节点索引值和连接到该节点的边的列表。我还有一个edge类,其中包含edge权重以及from节点和to节点。
节点声明:
class Node {
int value;
vector<Edge>& edges;
public:
Node(int input_value);
};
节点构造函数:
Node::Node(int input_value) {
value = input_value;
edges = {};
}
边缘声明:
class Edge: public Node {
int value;
// should I use int for node_from and node_to? nope
Node node_from;
Node node_to;
public:
Edge(int input_value, Node node_from_in, Node node_to_in);
};
边缘构造函数:
Edge::Edge(int input_value, Node node_from_in, Node node_to_in) {
value = input_value;
node_from = node_from_in;
node_to = node_to_in;
}
由于两个类是相互依赖的,所以我只转发声明class Edge;
来首先声明Edge,然后在Node类中通过引用将其传递。当我跑步时,出现以下错误:
/Users/sunshenggu/Documents/Atom/Graph/Graph.cpp:4:7: error: constructor for 'Node' must explicitly initialize the reference member 'edges'
Node::Node(int input_value) {
^
/Users/sunshenggu/Documents/Atom/Graph/Graph.hpp:18:17: note: declared here
vector<Edge>& edges;
^
/Users/sunshenggu/Documents/Atom/Graph/Graph.cpp:9:7: error: constructor for 'Edge' must explicitly initialize the base class 'Node' which does not have a default constructor
Edge::Edge(int input_value, Node node_from_in, Node node_to_in) {
^
/Users/sunshenggu/Documents/Atom/Graph/Graph.hpp:16:7: note: 'Node' declared here
class Node {
^
/Users/sunshenggu/Documents/Atom/Graph/Graph.cpp:9:7: error: constructor for 'Edge' must explicitly initialize the member 'node_from' which does not have a default constructor
Edge::Edge(int input_value, Node node_from_in, Node node_to_in) {
^
/Users/sunshenggu/Documents/Atom/Graph/Graph.hpp:26:8: note: member is declared here
但是当我将那些构造函数设置为默认值时,我得到了这些错误:
In file included from /Users/sunshenggu/Documents/Atom/Graph/Graph.cpp:2:
/Users/sunshenggu/Documents/Atom/Graph/Graph.hpp:20:27: error: only special member functions may be defaulted
Node(int input_value) = default;
^
/Users/sunshenggu/Documents/Atom/Graph/Graph.hpp:29:63: error: only special member functions may be defaulted
Edge(int input_value, Node node_from_in, Node node_to_in) = default;
^
/Users/sunshenggu/Documents/Atom/Graph/Graph.cpp:4:7: error: redefinition of 'Node'
Node::Node(int input_value) {
有人会指出我正确的方向吗?