Reputation: 17506
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.
Upvotes: 4
Views: 113
Reputation: 1656
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
Upvotes: 3
Reputation: 363
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
)
Upvotes: 0
Reputation: 275946
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.
Upvotes: 2