2012-04-15 151 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; 

这将调用了使用(参考)实际对象的过载,而不是指针本身