2014-12-08 3 views
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 연산자의 부모 연산자는 어떻게 호출합니까? 그저 나에게 "부모 :: 부모의 잘못된 사용"오류가 발생합니다.익명 액세스 Subobject C++ (cout)

+3

OS '<< static_cast (c)' –

+4

@PiotrS : 적절한 과부하를 호출하려면 c의 컨텍스트를 변경. 이 대답을하십시오. –

답변

4

c.Parent은 유효한 구문이 아니며 사용자의 operator<< 멤버 함수도 아닙니다.

ostream& operator<<(ostream& os, const Child& c) 
{ 
    os << static_cast<const Parent&>(c); 
    return os; 
}