2014-04-29 6 views
0

저는 기본 추상 클래스 인 Base를 가지고 있습니다.추상 클래스 오버로드 ostream 연산자

class Base 
{ 
protected: 
    string m_Name; 
public: 
    virtual string Name() { return m_Name; } 
    virtual string Type() = 0; 
    virtual bool isEqual(Base* rhs) = 0 ; 
    //virtual ostream& operator<< (ostream& out) const; 
}; 

나는 Base에서 상속 객체를 표시 할 operator <<에 과부하를하고 싶습니다. Base에서 상속받은 이러한 개체에는 operator <<으로 만 표시 할 수있는 개체가 있기 때문에 void print() 함수를 사용할 수 없습니다.

operator <<을 어떻게 오버로드 할 수 있습니까?

class Base 
{ 
public: 

    void print(std::ostream& o) const { /* do your stuff */ } 
    virtual ~Base() {} 
}; 

std::ostream& operator<<(std::ostream& o, const Base& b) 
{ 
    b.print(o); 
    return o; 
} 

아이디어는 각각의 파생 형이 필요에 따라 구현 print(ostream&)이다 :

+2

* 왜 * 가상 void 인쇄 (:: std :: ostream &) 함수를 사용할 수 없습니까? –

+0

[C++의 ostream 연산자 상속 및 오버라이드] (http://stackoverflow.com/questions/6027314/inheriting-and-overriding-ostream-operator-in-c) – juanchopanza

답변

5

일반적인 패턴은 가상 print 방법을 제공하고 그 ostream&<< 연산자를 사용하는 것이다.

관련 문제