Help with template class

Hello all,

I have written the following templet class, but I am having trouble getting the + overloader to work properly. Can someone please give me some assistance?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
using namespace std;

template <class T>
class myData
{
private:
	T data;
public:
	myData();
	myData(T);
	void set(T x);
	T get();

	// Overload +
	friend myData<T> operator+ (myData<T>, myData<T>);
	
	// Overload cin cout
	friend ostream& operator<< (ostream&, myData<T> obj);

	//friend istream &operator>> (istream&, myData<T> &obj);
	
};

template <class T>
myData<T>::myData()
{
	data = NULL;
}

template <class T>
myData<T>::myData(T a)
{
	data = a;
}

template <class T>
void myData<T>::set(T x)
{
	data = x;
}

template <class T>
T myData<T>::get()
{
	return data;
}

template <class T>
myData<T> operator+ (myData<T> op1, myData<T> op2)
{
	myData<T> temp;
	temp.data = op1.data + op2.data;
	return temp;
}

template <class T>
 ostream& operator<< (ostream& out, myData<T> obj)
{
	out << obj.data;
	return out;
}

 int main()
{
	myData<int> a;
	a.set(3);

	myData<int> b;
	b.set(4);

	myData<double> c;
	c.set(4.3);

	myData<double> d;
	d.set(5.7);

	myData<char> e;
	e.set('H');

	cout << a.get() << endl;
	cout << b.get() << endl;
	cout << c.get() << endl;
	cout << d.get() << endl;
	cout << e.get() << endl;
	cout << "a + b :" << a+b << endl;



	return 0;
}
Last edited on
use [code] and [/code] for your code!
To get your code to compile on codepad, I had to change lines 16, 20 and 30 : http://codepad.org/3EcZ7ymv
Now it works fine.
Sorry ceruleus for not properly posting. I will try to remember that going forward.

hamsterman, thank you so much, I have been beating my head against a wall for a few hours now. Can you tell me why you had to identify the overloads as a different template <class type>?
To be honest, I only did it because it worked. There is a (sort of) more appropriate way to do this. See http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Ffriends_and_templates.htm
Thanks for good topic !
Topic archived. No new replies allowed.