Overloading Operators
I may be adding to this. You can see a more in depth treatment of
overloading if you look at both my Rational number and Perry/Levin's version.
/**
cin >> val; means that the method >> which is a member of the class
specified by the left hand operand (in this case cin which
is of type istream) is invoked with an actual parameter of
the type of the right hand operand.
a + b; means that the + method of the class associated with a is called
with a parameter of type b ( a.add(b) ). In order to use the a + b
notation, I must define a function for the class of a that excepts
a parameter of type b.
**/
#include <iostream.h>
class Myclass
{
private:
int val;
public:
Myclass(int o = 0) {val = o;}
~Myclass() {};
Myclass add(Myclass a)
{
Myclass temp;
temp.val = val + a.val;
return(temp);
}
void output() {cout << val;}
void input() {cin >> val;}
Myclass operator + (Myclass a)
{
Myclass temp;
temp.val = val + a.val;
return(temp);
}
};
int main(void)
{
Myclass one, two;
cout << 3 + 4;
cout << "\nEnter an integer ";
one.input();
cout << "\none = ";
one.output();
two = one.add(one);
cout << "\ntwo = ";
two.output();
/** no operator "<<" matches these operands is the compiler error for the
first line of code. Similar messages are given for the other 2. Since
I want to be able to use these operators for my class instead of the
more cumbersome one.add(), etc., I need some mechanism for defining
the operators so that the operator (think function) has a version that
uses the operands of the type I want.
cout << one;
cin >> two;
two = one + one;
**/
/** after adding the operator + method to class Myclass **/
two = one + one + one;
cout << "\nNow two = ";
two.output();
cout << endl << endl;
return(0);
}