C++:重载运算符函数的编写,尤其是++、--的前后缀问题

#include<iostream>
#include<string>
using namespace std;
class Complex {
private:
	int real;
	int imag;
public:
	Complex(int r, int i) {
		real = r;
		imag = i;
	}
	void show() {
		cout << "real=" << real << " imag=" << imag << endl;
	}
	Complex operator++()//前缀++ 
	{
		++real;
		++imag;
		return *this;
	}
	Complex operator++(int);//后缀++
	friend Complex operator+(Complex&, Complex&);//复数相加
	friend Complex operator-(Complex&, Complex&);//复数相减
	friend Complex operator+(Complex& A, int C)//复数+整数(复数在前)
	{
		Complex temp(A);
		temp.real += C;
		return temp;
	}
	friend Complex operator+(int, Complex&);//整数+复数(整数在前)
	friend Complex operator-(Complex&, int);//复数-整数(复数在前)
	friend Complex operator-(int C, Complex& A) //整数-复数(整数在前)
	{
		Complex temp(A);
		temp.real -= C;
		return temp;
	}
	Complex operator--() //前缀--
	{
		--real;
		--imag;
		return *this;
	}
	Complex operator--(int);//后缀--
	friend Complex operator*(Complex& A, Complex& B)//复数相乘 
	{
		Complex temp(A);
		temp.real = A.real * B.real - A.imag * B.imag;
		temp.imag = A.real * B.imag + A.imag * B.real;
		return temp;
	}
	friend Complex operator/(Complex& A, Complex& B)//复数相除
	{
		Complex temp(A);
		temp.real = (A.real * B.real - A.imag * B.imag) / (B.imag * B.imag + B.real * B.real);
		temp.imag = (A.real * B.imag + A.imag * B.real ) / (B.imag * B.imag + B.real * B.real);
		return temp;
	}
};
Complex	Complex::operator++(int) {
	Complex temp(*this);
	real++;
	imag++;
	return temp;
}
Complex operator+(Complex& A, Complex& B) {
	Complex temp(A);
	temp.real += B.real;
	temp.imag += B.imag;
	return temp;
}
Complex operator-(Complex& A, Complex& B) {
	Complex temp(A);
	temp.real -= B.real;
	temp.imag -= B.imag;
	return temp;
}
Complex operator+(int C, Complex& A) {
	Complex temp(A);
	temp.real += C;
	return temp;
}
Complex operator-(Complex& A, int C) {
	Complex temp(A);
	temp.real -= C;
	return temp;
}
Complex Complex::operator--(int) {
	Complex temp(*this);
	real--;
	imag--;
	return temp;
}
int main() {
	Complex c1(1, 2), c2(3, 4), c3(5, 6), c4(7, 8), c5(9, 1),c6(0,0);
	Complex& c7=c1;
	c6 = c1 +c2;
	c6.show();
	c6 = c1 - c2;
	c6.show();
	c6 = c5++;
	c6.show();
	c5.show();
	c6 = c4--;
	c6.show();
	c4.show();
	c6 = c2 * c1;
	c6.show();
	c6 = c2 / c1;
	c6.show();

}

运行结果:

real=4 imag=6
real=-2 imag=-2
real=9 imag=1
real=10 imag=2
real=7 imag=8
real=6 imag=7
real=-5 imag=10
real=-1 imag=2

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值