二元运算符的重载
重载“-”运算符,使该运算符可以直接求出任意两点p1(X,Y)和p2(X,Y)之间的距离d,即d=p1-p2。
#include <iostream>
using namespace std;
class complex
{
public:
complex ()
{
real=0;
imag=0;
}
complex(double r,double i)
{
real=r;
imag=i;
}
complex operator -(complex &c2);
void display();
private:
double real;
double imag;
};
complex complex::operator -(complex &c2)
{
return complex(real-c2.real,imag-c2.imag);
}
void complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main()
{
complex c1(3,4),c2(5,-10),c3;
c3=c1-c2;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
cout<<"c3=";
c3.display();
return 0;
}