2012-12-13 79 views
3

我有这个类:C++ “<<” 操作符重载

// in Platform.h 
class Platform 
{ 
private: 
    float y; 
    float xi; 
    float xf; 
public: 
    Platform(float y, float xi, float xf); 
    virtual ~Platform(void); 
    float getxi(); 
    float getxf(); 
}; 

而且我希望能够做到这一点:

Platform* p = new Platform(1.0,2.0,3.0); 
cout << p; // should it be *p? 

我试图超载 “< <” 运营商,像这样:

// in Platform.cpp 
std::ostream& operator<<(std::ostream& out, Platform* p) 
{ 
    out << "Platform: xi=" << p->getxi() << ", xf=" << p->getxf() << std::endl; 
    return out; 
} 

但这只是打印出内存地址(当然,因为p是指针......)。 我很确定上述函数根本没有被调用。

回答

2

是做了* P:

so cout << *p ; 

和常规操作是......

std::ostream& operator << (std::ostream& out, const Platform& p) { } 

您还需要在头文件中导出此所以它是外部可见。地址:

friend std::ostream& operator<<(std::ostream& out, Platform* p) ; 

要Platform.h

+3

*“否则,模板搜索并找到指针打印功能。” *不,他的过载,应改为调用。我猜,从Yakk说的那个地方他不知道从哪里来。 – Pubby

+0

是的,我的错误。我没有注意到*和第一次阅读它... –

+0

我应该在调用'cout << * p'的文件中添加'#include“Platform.cpp”'吗? –

2

超载声明必须是从您使用它可见。将其更改为Platform const&并在您使用时使用*p,因为这是常规方式。

0

其实这个工作在g ++ 4.7.2中,但也许它依赖于编译器。你可以这样做:

// in Platform.cpp 
std::ostream& operator<<(std::ostream& out, Platform& p) 
{ 
    out << "Platform: xi=" << p.getxi() << ", xf=" << p.getxf() << std::endl; 
    return out; 
} 

和打印使用间接(*p