4

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.

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

"Otherwise the template searches for and finds the pointer print function." No, his overload should be called instead. I'm guessing it wasn't visable from where he was calling from as Yakk said.
Should I add #include "Platform.cpp" in the file that calls cout << *p ?
No, add a "friend std::ostream& operator<<(std::ostream& out, Platform* p ) ; " to Platform.hpp
@DavidMokonBond: Why would you want this to be a friend if it only uses public functions?
Reasonable point, but I copied that from some of my code and I think its pretty standard for that having access to private data. Really depends though of course... If you have a nice system where you have gettters for everything you need sure...
2

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.

Comments

0

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.