我在派生的clases ex:
中有一个操作员<<
的问题
如果我有
class Base
{
//......
friend ostream& operator<<(ostream& out,Base &B)
{
return out<<B.x<<B.y<</*........*/<<endl;
}
//......
};
是下属的?
class Derived: public Base
{
//......
friend ostream& operator<<(ostream& out,Derived &DERIVEDOBJECT)
{
return out<<DERIVEDOBJECT<<DERIVEDOBJECT.nonderivedvar1 <</*.....*/<< endl;
}
}
或将DERIVEDOBJECT
放在<<
运算符中不会导致<<
将其重新定义为基类的参考?
答案 0 :(得分:10)
你通常想要的是这样的:
class Base {
virtual std::ostream &write(std::ostream &os) {
// write *this to stream
return os;
}
};
std::ostream &operator<<(std::ostream &os, Base const &b) {
return b.write(os);
}
然后,如果需要,派生类会覆盖write
。
答案 1 :(得分:1)
这将导致递归调用:
out<<DERIVEDOBJECT
我愿意:
friend ostream& operator(ostream& out,Derived &DERIVEDOBJECT)
{
return out << static_cast<Base&>(DERIVEDOBJECT)
<< DERIVEDOBJECT.nonderivedvar1
<<.....<< endl;
}
PS。空格和小写字母是你的朋友 按照惯例,全部大写的标识符都是宏,因此您可以通过使用正常变量的所有大写标识符来混淆人们。
答案 2 :(得分:0)
您可以通过 upcasting 到基类型实现预期结果:
struct base {};
std::ostream& operator<<( std::ostream& o, base const & b ) {
return o << "base";
};
struct derived : base {};
std::ostream& operator<<( std::ostream& o, derived const & d ) {
return o << static_cast<base&>(d) << " derived";
}
int main() {
derived d;
std::cout << d << std::endl; // "base derived"
}