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?

tux3
  • 7,171
  • 6
  • 39
  • 51
Archarious
  • 43
  • 7

1 Answers1

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;
Barry
  • 286,269
  • 29
  • 621
  • 977
  • Yes that is correct. Now I understand how it works. Thank you very much. – Archarious Apr 10 '15 at 18:47
  • 1
    Most likely, the OP doesn't really want a pointer at all. There's still the issue of the `friend` declaration mismatching the definition. – chris Apr 10 '15 at 18:47
  • Not absolutely understand what you mean – Archarious Apr 10 '15 at 18:55
  • @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](http://coliru.stacked-crooked.com/a/9385508ad34ae1ef). I suggest reading about [what that actually declares](http://en.cppreference.com/w/cpp/language/friend). – chris Apr 10 '15 at 18:57
  • @chris, ok, i understood! Thank you for explain and for article! – Archarious Apr 10 '15 at 19:10
  • @Archarious: After fixing the pointer, you might want to look at this answer to a similar question http://stackoverflow.com/a/4661372/36565 – David Rodríguez - dribeas Apr 10 '15 at 22:30