我使用 4 个类实现了边(如图中所示):Node、Node_Linkedlist、Edge、Edge_Linkedlist。 Node 有一个私有(private) int 成员,Edge 有 2 个 Node 的引用成员:
private:
Node& in;
Node& out;
Edge 有 2 个工作构造函数,因此 Edge 支持 Node
和const Node
.
Edge(Node& tmpin, Node& tmpout) : in(tmpin),out(tmpout) {};
Edge(const Node& tmpin, const Node& tmpout) : in(Node(tmpin)),out(Node((tmpout))) {};
<<
运算符:
ostream& operator<<(ostream& out, const Edge& node)
{
out<<node.in<<endl;
return out;
}
这适用于Node
但不适用于const Node
。在 const Node
,当调试器进入操作符的范围时,它会转储 Node.js 的 int 值。为什么运算符(operator)不为const Node
工作?
最佳答案
您的代码无效 - 您正在将非常量引用绑定(bind)到构造函数中的临时对象 - Node(tmpin)
和 Node(tmpout)
是临时对象 -并遇到未定义的行为。要支持 const
,您需要将成员设置为 const
、指针,或者将它们设置为对象而不是引用。
就我个人而言,我会让它们成为智能指针:
private:
std::shared_ptr<Node> in;
std::shared_ptr<Node> out;
关于c++ - 如何对类的 const 实例使用打印运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10436799/