我正在尝试用C ++创建一个图形类。我将每个节点的边存储为Edge类的向量。 Edge类有一个getWeight()
函数,但它返回了奇怪的值。
我认为它与获取边缘的副本而不是已经分配的实际边缘有关。
继承人类:
#ifndef EDGE_INCLUDED
#define EDGE_INCLUDED
#include "Node.h"
class Node;
class Edge {
private:
Node endpoint;
double weight;
public:
Edge();
Edge(const Edge &edge);
double getWeight() const;
void setWeight(double weight);
};
#endif // End EDGE_INCLUDED
/////////////////////////////////////////////////////////////////
#include "Edge.h"
#include "Node.h"
Edge::Edge(){}
Edge::Edge(const Edge &edge) {}
double Edge::getWeight() const { return this->weight; }
void Edge::setWeight(double weight) { this->weight = weight; }
这里是Node类
#ifndef NODE_INCLUDED
#define NODE_INCLUDED
#include <string>
#include <vector>
class Edge;
class Node {
private:
std::string label;
std::vector<Edge> edges;
public:
const std::string getLabel() const;
void setLabel(std::string label);
const size_t degree() const;
std::vector<Edge> getEdges();
void setEdges(std::vector<Edge> edges);
};
#endif // End NODE_INCLUDED
/////////////////////////////////////////////////////////
#include "Node.h"
#include "Edge.h"
const std::string Node::getLabel() const { return this->label; }
void Node::setLabel(std::string label) { this->label = label; }
const size_t Node::degree() const { return this->edges.size(); }
std::vector<Edge> Node::getEdges() { return this->edges; }
void Node::setEdges(std::vector<Edge> edges) { this->edges = edges; }
最后这里是主要的
#include <iostream>
#include "Edge.h"
#include "Node.h"
int main()
{
Edge edge1;
Node node;
std::vector<Edge> edges;
edge1.setWeight(2.0);
edges.push_back(edge1);
node.setEdges(edges);
std::vector<Edge> e = node.getEdges();
for (auto i : node.getEdges())
std::cout << i.getWeight() << std::endl;
}
很抱歉发布了这么多代码,但我希望有人能够看到我在哪里错了。 任何人都可以看到我的错误并指出我更好的设计吗?
答案 0 :(得分:1)
在Edge
的构造函数中,您不能初始化成员weight
。因此,您正在看到未初始化的垃圾值。
将它们更改为:
Edge::Edge() : weight(0.0) {}
Edge::Edge(const Edge &edge) : weight(edge.weight) {}