Доступ к анонимному подобъекту C++ (cout)

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

Как позвонить оператору Parent внутри оператора Child? Это просто дает мне ошибку "неверное использование Parent::Parent"

1 ответ

Решение

c.Parent не является допустимым синтаксисом, как и ваш operator<< функция-член. Чтобы вызвать правильную перегрузку, измените контекст c:

ostream& operator<<(ostream& os, const Child& c)
{
    os << static_cast<const Parent&>(c);
    return os;
}
Другие вопросы по тегам