0

I got confused in overloading the ostream operator<< for my template class. (unnecessary code deleted)

sparseArray2D.h:

#include <iostream> using namespace std; template <typename T> class sparseArray2D { private: //... public: //... friend ostream& operator << (ostream&, const sparseArray2D<T>&); //... } template <typename T> ostream& operator << (ostream& os, const sparseArray2D<T> &_matrix) { //... os<<"Overloaded operator works"; return os; }; 

and main:

#include "sparseArray2D.h" int _tmain(int argc, _TCHAR* argv[]) { //... sparseArray2D<int> *matrX = new sparseArray2D<int>(10, 9, 5); cout << matrX; //... } 

No errors and no warnings in VS2012, but in the console I have 8 symbols as link or pointer at object. Like "0044FA80".

What's going wrong?

2
  • Note: A pointer is no object (C++) Commented Apr 10, 2015 at 18:36
  • Why not sparseArray2D<int> matrX(10, 9, 5); Commented Apr 10, 2015 at 18:43

1 Answer 1

2

That's because you're overloading (not reloading) on sparseArray2D<T>, but that is not what matrX is:

sparseArray2D<int> *matrX = new sparseArray2D<int>(10, 9, 5); // ^^ cout << matrX; 

matrX is a pointer. As such, you're just streaming the pointer - which by default logs its address... which is apparently 0x0044FA80.

What you want is:

cout << *matrX; 
Sign up to request clarification or add additional context in comments.

6 Comments

Yes that is correct. Now I understand how it works. Thank you very much.
Most likely, the OP doesn't really want a pointer at all. There's still the issue of the friend declaration mismatching the definition.
Not absolutely understand what you mean
@Archarious, To create a simple object, there's no need for a pointer at all (and Neil Kirk gave an alternative in another comment). Your definition of operator<< does not define the one you declared in your class, either, as evident by a linker error. I suggest reading about what that actually declares.
@chris, ok, i understood! Thank you for explain and for article!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.