Nov 10, 2011 at 5:57pm UTC
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 Nov 10, 2011 at 7:19pm UTC
Nov 10, 2011 at 6:15pm UTC
use [code] and
[/code] for your code!
Nov 10, 2011 at 7:22pm UTC
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>?