2012-04-15 250 views
1

我有一個輕微的問題,我的< <運營商沒有被正確調用。虛擬<<運營商

這是我有:

class SomeInterface 
{ 
    friend std::ostream& operator<<(std::ostream& str, const SomeInterface& data); 

    protected: 
     virtual void print(ostream& str) const = 0; 
}; 

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

調用代碼看起來是這樣的:

SomeInterface* one = new someConcrete(); 
cout << one; 

的< <重載函數我希望會被調用的接口上沒有,更別說調度直到派生類。

回答

3

嘗試:

cout << *one; 

你的代碼是要求打印指針,而你operator<<需要const SomeInterface&參考。

+0

謝謝...我早該猜到它是打印地址等之後垃圾。 – 2012-04-15 22:54:14

0

您正在致電std::ostream& operator<< (std::ostream& o, void*);,因爲one的類型是一個指針。

嘗試:

cout << *one; 

這將調用了使用(參考)實際對象的過載,而不是指針本身