它经常作为类的友元函数被重载。有什么方法可以将其重载为成员函数吗?
有什么方法可以将其重载为成员函数吗?
假设你有课Foo
并且您想使用:
Foo foo;
std::cout << foo;
不,它不能。
仅当第一个参数是类的对象时,成员函数重载才有效。对于流插入运算符,第一个参数是流,而不是类的对象。
如果你想使用:
Foo foo;
foo << std::cout;
是的,它可以定义为成员函数。
在涉及派生类的情况下,非成员函数和虚成员函数可以结合使用,效果很好。
struct Shape
{
// Member function that can be overridden by derived classes.
virtual std::ostream& operator<<(std::ostream& os) const = 0;
};
// Non-member function that makes use of member functions.
std::ostream& operator<<(std::ostream& os, Shape const& shape)
{
return shape << os;
}
struct Rectangle : public Shape
{
virtual std::ostream& operator<<(std::ostream& os) const
{
// Do the need full to stream a Rectangle.
// ...
return os;
}
};
struct Ellipse : public Shape
{
virtual std::ostream& operator<<(std::ostream& os) const
{
// Do the need full to stream an Ellipse.
// ...
return os;
}
};
Usage:
Rectangle r;
Ellipse e;
std::cout << r << std::endl;
std::cout << e << std::endl;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)