Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 304
Maria Ines Parnisari Avatar asked Sep 07 '25 18:09

Maria Ines Parnisari


1 Answers

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

like image 150
David Mokon Bond Avatar answered Sep 09 '25 21:09

David Mokon Bond