Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何超载<&书信电报;操作人员_C++_Printing_Overloading - Fatal编程技术网

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);