Complex_operator
创建一个复数类Complex,并重载后缀“--”运算符,将其重载为友元函数,实现复数的实部减1和虚部减1。</br>
Complex类如下,请补充重载后缀“--”运算符,并用main函数测试。</br>
class Complex
{
protected:
double r;//实部
double i;//虚部
public:
Complex(double x = 0.0, double y = 0.0)
{
r = x;
i = y;
}
void show()
{
cout<< "(" << r << "," << i <<")";
}
};
int main()
{
Complex c1(10.0, 20.0), c2;
c2 = c1--;
c1.show();
cout<< endl;
c2.show();
cout<< endl;
return 0;
}
代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<iomanip>
#include<cmath>
using namespace std;
class Complex
{
//友元 重载后置递减
friend Complex operator--(Complex& c, int);//int占位符区分前置和后置
protected:
double r;//实部
double i;//虚部
public:
Complex(double x = 0.0, double y = 0.0)
{
r = x;
i = y;
}
void show()
{
cout << "(" << r << "," << i << ")";
}
};
//后置返回值 因为要创建临时变量保存值,要是返回引用后续临时变量就非法了
Complex operator--(Complex& c, int)
{
Complex temp(c);//创建一个临时对象来保存当前值
c.i--;
c.r--;
return temp;//返回递减前的值
}
int main()
{
Complex c1(10.0, 20.0), c2;
c2 = c1--;
c1.show();
cout << endl;
c2.show();
cout << endl;
return 0;
}