3
class Parent
{
    ...
    friend ostream& operator<<(ostream&, const Parent&);
};

class Child : public Parent
{
    ...
    friend ostream& operator<<(ostream&, const Child&);
};

ostream& operator<< (ostream& os, const Parent& p)
{
    os << ... ;
    return os;
}

ostream& operator<< (ostream& os, const Child& c)
{
    os << c.Parent << ... ;    // can't I access the subobject on this way?
    return os;
}

如何在 Child 运算符中调用 Parent 运算符?这只是给了我错误“无效使用 Parent::Parent”

4

1 回答 1

4

c.Parent不是有效的语法,您operator<<的成员函数也不是。要调用正确的重载,请更改的上下文c

ostream& operator<<(ostream& os, const Child& c)
{
    os << static_cast<const Parent&>(c);
    return os;
}
于 2014-12-08T13:30:41.290 回答