运算符重载是c++的又一个先进功能。它使用户可以对自己定义的对象使用运算符像对int、float使用一样方便、简洁、形象,增加程序的可读性。重载运算符既可以用友元函数,也可以用成员函数。推荐使用成员函数进行重载,因为友元函数破坏了c++的封装性。自写程序下:
//overloading operator
#include <iostream.h>
class coor
{
friend istream &operator>> ( istream &, coor & );
friend ostream &operator<< ( ostream &, coor & );
public:
coor( int = 0, int = 0 );
coor operator+ ( coor & );
coor operator- ( coor & );
bool operator== ( coor & );
bool operator!= ( coor & );
private:
int x;
int y;
};
istream &operator>> ( istream &input, coor &d )
{
input.ignore();
input >> d.x;
input.ignore();
input >> d.y;
input.ignore();
return input;
}
ostream &operator<< ( ostream &output, coor &d)
{
output << '(' << d.x
<< ',' << d.y
<< ')' << endl;
return output;
}
coor::coor( int X, int Y)
{
x = X;
y = Y;
}
coor coor::operator+ ( coor &a )
{
coor c;
c.x = this->x + a.x;
c.y = this->y + a.y;
return c;
}
coor coor::operator- ( coor &a )
{
coor c;
c.x = this->x - a.x;
c.y = this->y - a.y;
return c;
}
bool coor::operator== ( coor &a )
{
if( this->x == a.x && this->y == a.y )
return true;
else return false;
}
bool coor::operator!= ( coor &a )
{
return !( *this == a );
}
int main()
{
coor num1(5,9), num2(5,9), sum;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
cout << "sum = " << sum << endl;
if( num1 == num2 )
cout << "num1 is equal to num2" << endl;
if( num1 != num2 )
cout << "num1 is not equal to num2" << endl;
cout << "type the num2: " <<endl;
cin >> num2;
cout << "num2 = " << num2 <<endl;
if( num1 == num2 )
cout << "num1 is equal to num2" << endl;
if( num1 != num2 )
cout << "num1 is not equal to num2" << endl;
sum = num1 + num2;
cout << "num1 + num2 = sum = " << sum << endl;
return 0;
}