简体   繁体   中英

C++ “<<” operator overload

I've got this class:

// 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();
};

And I want to be able to do this:

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

I tried overloading the "<<" operator, like this:

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

But this just prints a memory address (of course, because p is a pointer...). I'm quite sure that the above function isn't being called at all.

Yes do a *p:

so cout << *p ;

And the conventional operator is...

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

You also need to export this in the header file so it is visible outside. Add:

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

To Platform.h

The overload declaration needs to be visible from where you use it. Change it to Platform const& and use *p while you are at it, because that is the conventional way.

Actually this works in g++ 4.7.2 but perhaps it depends on the compiler. You can do:

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

And print using indirection ( *p )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM