0

This code work but when I define the ostream outside the class, I have to take out , I want to know the reason.

So it works when the definition is:

ostream& operator << (ostream &s, const Point<DataType>& p)

I think it should be:

ostream& operator << <DataType> (ostream &s, const Point<DataType>& p);

The following is the complete code:

#include <iostream>
using namespace std;

template <class DataType>

class Point{
protected:
   double _x;
   double _y;
   DataType _data;
public:
   Point(double x, double y, const DataType& data);
   DataType& data();
   friend ostream& operator << <DataType> (ostream &s, const Point<DataType>& p);
   };

template <class DataType>
Point<DataType>::Point(double x, double y, const DataType& data)
{
    _x = x;
    _y = y;
    _data = data;
}

template <class DataType>
DataType& Point <DataType>::data()
{
    return _data;
}


template <class DataType>
ostream& operator << (ostream &s, const Point<DataType>& p)
{
    s << "(" << p._x << "," << p._y << "," << p._data << ")";
    return s;
}


void main()
{
    Point <int> p(5.0, 10.0, 7);
    cout << p << endl;
}
P C
  • 1

1 Answers1

0

You can use:

  friend ostream& operator<< <DataType>(ostream &s, const Point& p);

if you forward declare the function. I think this is what you are looking for.

Forward declare the class.

template <class DataType> class Point;

Forward declare the function.

template <class DataType> 
ostream& operator << (ostream &s, const Point<DataType>& p);

Now you can use friend the way you were intending to.

template <class DataType>

class Point{
   protected:
      double _x;
      double _y;
      DataType _data;
   public:
      Point(double x, double y, const DataType& data);
      DataType& data();
      friend ostream& operator<< <DataType>(ostream &s, const Point& p);
};

template <class DataType>
ostream& operator << (ostream &s, const Point<DataType>& p)
{
   s << "(" << p._x << "," << p._y << "," << p._data << ")";
   return s;
}

BTW, you should use:

int main()

instead of

void main()
R Sahu
  • 204,454
  • 14
  • 159
  • 270