定义一个复数类 Complex,重载运算符“-”,使之能用于复数与实数的减法运算。参加运算的两个操作数一个是类的对象,一个是实数,顺序任意。例如:i-c,c-i 均合法(其中,c 为复数类的对象,i 为实数)。
减法规则:复数实部与实数相减,复数虚部不变。
#include<iostream>
using namespace std;
class Complex {
private:
double real;
double image;
public:
Complex(double r = 0.0, double i = 0.0);
void print();
friend Complex operator-(double y, Complex &c);
friend Complex operator-(Complex &d, double x);
};
Complex::Complex(double r, double i)
{
real = r; image = i;
}
Complex operator-(double y,Complex &c)
{
Complex temp;
temp.real = y - c.real;
temp.image = c.image;
return temp;
}
Complex operator-(Complex &d,double x)
{
Complex temp;
temp.real = d.real - x;
temp.image = d.image;
return temp;
}
void Complex::print()
{
cout << real;
if (image > 0) cout << "+";
if (image != 0) cout << image << "i" << endl;
}
int main()
{
Complex A1(1.2, 3.4), A3, A4;
A3 = 5.0 - A1;
A4 = A1 - 0.3;
A3.print();
A4.print();
return 0;
}
主要运用有元运算符重载函数的相关方法,Complex operator-(Complex &d,double x) 这里的x前不能加引用声明符&,否则会出现运行错误。