我想在C++中創建一個圖類。我將每個節點的邊緣存儲爲Edge類的向量。 Edge類有getWeight()
函數,但它返回奇怪的值。從對象的向量中獲取字段C++
我認爲這與獲取邊緣副本而不是已分配的實際邊緣有關。
繼承人的邊緣種類:
#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;
}
抱歉張貼這麼多的代碼,但我希望有人能夠看到我哪裏錯了。 任何人都可以看到我的錯誤,並指出我更好的設計?
這一切都很好,很正常,但是你怎麼用這個圖?您的邊緣具有端點的cipies,並且每個端點副本都具有其邊緣的副本,並且每個邊緣的每個副本都具有*自己的*端點的副本以及... –