2012-04-28 38 views
4

所以,我有兩個類:調用ostream的友元函數

class Base { 
    private: 
     int number; 
    public: 
     friend ostream & operator<<(ostream & output, const Base &n); 
} 

ostream & operator<<(ostream & output, const Base &n) { 
    output<<n.a<<endl; 
    return output; 
} 

class Child : Base { 
    private: 
     int second; 
    public: 
     friend ostream & operator<<(ostream & output, const Child &n); 

} 

ostream & output<<(ostream & output, const Child &n) { 
    output<<n.second<<Base:: ????<<endl; 
    return output; 
} 

我的問題是,我怎麼能調用基類的友元函數從子類來輸出它的內容:

output<<n.second<<Base:: ????<<endl 

感謝提前:)

回答

3

如果你不願意鑄造:

ostream & operator<<(ostream & output, const Child &n) { 
    const Base& b(n); 

    output<< n.second << b << endl; 
    return output; 
} 

順便說一句,在總體上可能是最好離開把std::endl以流的調用者。

3
output<<n.second<<static_cast<const Base&>(n)<<endl; 
+0

爲什麼啊你爲什麼要通過指針? 'static_cast (n)'非常好,不太冗長。 – 2012-04-28 20:46:01

+0

@MatthieuM。固定。 – David 2012-04-28 21:16:01

2

其實......我會提出一個替代方案。

存在具有不虛函數的基類的小點,所以讓我們只添加一個虛擬方法:)

class Base { 
public: 
    virtual void print(std::ostream& out) const { /**/ } 

}; 

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

現在,我們在派生類中重寫此:

class Derived: public Base { 
public: 
    virtual void print(std::ostream& out) const override { 
     out << /* specific */; 
     this->Base::print(out); /* base */ 
    } 
};