[英]overloading operator<<. This operator is not a friend of class
I have to overload:我必须超载:
ostream& operator<<();
This must be implement as method so I can't do it as friend.这必须作为方法来实现,所以我不能作为朋友来做。 How to do it?怎么做?
If you will write this operator as a member function then it will only confuse users because the left operand of the operator will be an object of your class type instead of std::ostream.如果您将此运算符编写为成员函数,那么它只会使用户感到困惑,因为运算符的左操作数将是您的类类型的对象,而不是 std::ostream。 So you could write your own member function instead of the operator.因此,您可以编写自己的成员函数而不是运算符。 For example例如
class YourClass
{
public:
std::ostream & out( std::ostream &os ) const
{
// some output
return os;
}
//...
};
You could also use this function inside the definition of the operator as a non-member function of the class.您还可以在运算符的定义中使用此函数作为类的非成员函数。 For example例如
std::ostream & operator <<( std::ostream &os, const YourClass &obj )
{
return obj.out( os );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.