C++ 如何超载<&书信电报;操作人员
我正试图使汽车超载 当我试图打印出来时,我正在打印一个节点,我不知道这是否与它有关 确实如此C++ 如何超载<&书信电报;操作人员,c++,printing,overloading,C++,Printing,Overloading,我正试图使汽车超载 当我试图打印出来时,我正在打印一个节点,我不知道这是否与它有关 确实如此 Node* n = ...; std::cout << n; 这需要将print更改为const成员函数 我还建议将print的返回类型更改为std::ostream& std::ostream& print(std::ostream& out) const; 现在,实现如下所示: std::ostream& Node::print(std::ostream&am
Node* n = ...;
std::cout << n;
这需要将print
更改为const
成员函数
我还建议将print
的返回类型更改为std::ostream&
std::ostream& print(std::ostream& out) const;
现在,实现如下所示:
std::ostream& Node::print(std::ostream& out)
{
return (out<< freq << " " << input<<" " << Left<< " " << Right<< std::endl);
}
inline std::ostream& operator<<(std::ostream& out, Node const& n)
{
return n.print(out);
}
inline std::ostream& operator<<(std::ostream& out, Node const* n)
{
return (out << *n);
}
std::ostream&Node::打印(std::ostream&out)
{
return(out为什么要使用print函数?相反,您可以对friend函数使用重载。以前在实现此功能时,我需要像这样通过const引用传递对象const Node&name
,并返回ostream&
假设freq和input是类的成员,那么您的代码在.cpp中应该是这样的:
ostream& operator<<(ostream& out, const Node& n)
{
return out<<n.freq<< " " <<n.input<<" "<<n.Left<<" "<< n.Right;
}
ostream&operatorFYI,应通过常量引用传递节点
,例如const Node&n
。此外,将Node::print
更改为常量方法:void Node::print(ostream&out)const
实际问题是什么?只需注意:如果您重载运算符只需注意:const Node&n
重载是金标准,但我可能会避免const Node*n
重载,因为它会阻止您在如下场景中打印指针值本身:Node*n=new Nod我明白了,所以你建议只保留第一个,当想要打印指针数据时,我会准确地使用,这是最好的方法。OP使用print
函数的方法没有问题。
std::cout << n;
std::cout << *n;
inline ostream& operator<< (ostream& out, Node* n)
{
return (out << *n);
}
inline ostream& operator<<(ostream& out, Node const& n);
std::ostream& print(std::ostream& out) const;
std::ostream& Node::print(std::ostream& out)
{
return (out<< freq << " " << input<<" " << Left<< " " << Right<< std::endl);
}
inline std::ostream& operator<<(std::ostream& out, Node const& n)
{
return n.print(out);
}
inline std::ostream& operator<<(std::ostream& out, Node const* n)
{
return (out << *n);
}
ostream& operator<<(ostream& out, const Node& n)
{
return out<<n.freq<< " " <<n.input<<" "<<n.Left<<" "<< n.Right;
}
friend ostream& operator<<(ostream& out, const Node& n);
ostream& operator<<(ostream& out, const Node* n)
{
return out<<n->freq<< " " <<n->input<<" "<<n->Left<<" "<< n->Right;
}
friend ostream& operator<<(ostream& out, const Node* n);