A few questions on operator overloading:
make our object behaves just like int object (why? how?)
can we do cascading operation, e.g. cout << clock1 << clock2?
what makes it possible?
can you change the code to make it work or make it fail?
why do you need to declare friend for << ?
if we do not have private members in <<, do we need to declare friend
can we move non-friend global << function outside the class definition?
global operator overloading vs member operator overloading?
do you know two ways of doing operator overloading?
can we overload an operator both ways? (such as operator+ in our example below)
why << can only work in global form, but not the other?
can we do clock1.setmin.setsec? (hope you know what I mean :-) clock has hr,min,sec)
class complexType
{
friend ostream& operator<< (ostream&, const complexType&);
friend istream& operator>> (istream&, complexType&);
friend complexType operator+(const complexType& one, const complexType& two);
public:
void setComplex(const double& real, const double& imag);
complexType(double real = 0, double imag = 0); // constructor with default parameters
complexType operator-(const complexType& two);
complexType operator-(int x);
complexType operator+ (int x);
private:
double realPart; //variable to store the real part
double imaginaryPart; //variable to store the imaginary part
};
--------------------------------
A simple client...
complexType num1(1,2),num2(3),num3;
num3 = num1+num2;
cout << "N1+N2=" << num3 << endl;
cout << "N1-N2=" << num1-num2 << endl;
cout << num1-5 << endl;
cout << num1+5 << endl;
cin >> num2;
one constructor can support multiple form of invocation
complexType(double real = 0, double imag = 0);
One constructor with parameter initialization allows us to have 3 ways of creating complex objects, such as
complexType num1(1,2), num2(3), num3;
one operator can be overloaded as global or member function
Operator can be overloaded as "global" function or "member" function. In the example, operator+ is a global function (having 2 arguments), operator- is a member with one argument. (hmmm, why two arguments versus one?)
There is no difference in usage (but performance is better with member). In general, we should use "member" function for operator overloading if possible.
one operator can be overloaded many times as long as it conforms to the general function overloading constraints
complexType operator-(int x);
We can further overload operator- with other functionality, like subtract an int from complex object in our example above. The semantic of it is totally up to the class implementation. Note that this is the "function overloading" capability of C++ language. After all, operator- is a function.
Having both global and member operator overloading is also possible, such as the operator+ in the example. I don't know why would you want do that though.
One complex implementation source code is in the attachment of "storing objects" note.