理解为什么前置++后置++问题,为什么最终都实现了+1问题

#include <iostream>
using namespace std;

class Complex
{
private:
	int a;
	int b;
	//全局函数 重载+运算符
	friend Complex operator+(Complex &c1, Complex &c2);
	//重载 前置++
	friend Complex& operator++(Complex &c1);
	friend Complex operator++(Complex &c1, int);
public:
	Complex(int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
	}

	Complex(const Complex &c)
	{
		this->a = c.a;
		this->b = c.b;
		cout << "拷贝构造函数" << endl;
	}
	void printCom()
	{
		cout << a << " + " << b << "i" << endl;
	}
	~Complex()
	{
		cout << "析构函数" << endl;
	}
public:

	//成员函数法 实现 -运算符重载
	Complex operator-(Complex &c2)
	{
		Complex tmp(this->a - c2.a, this->b - c2.b);
		return tmp;
	}

	//前置--
	Complex& operator--()
	{
		this->a--;
		this->b--;
		return *this;
	}

	//后置--
	Complex operator--(int)
	{
		Complex tmp = *this;
		this->a--;
		this->b--;
		return tmp;
	}
};

//全局函数法 实现 + 运算符重载
Complex operator+(Complex &c1, Complex &c2)
{
	Complex tmp(c1.a + c2.a, c1.b + c2.b);
	return tmp;
}

//前置++
Complex& operator++(Complex &c1)
{
	c1.a++;
	c1.b++;
	return c1;
}

//后置++
Complex operator++(Complex &c1, int)
{
	//先使用 在让c1加加
	Complex tmp = c1;//保存对象前一刻的状态
	//return c1;
	c1.a++;
	c1.b++;
	return tmp;
}

/*
全局函数、类成员函数方法实现运算符重载步骤
1)要承认操作符重载是一个函数,写出函数名称
2)根据操作数,写出函数参数
3)根据业务,完善函数返回值(看函数是返回引用 还是指针 元素),及实现函数业务
*/
void main()
{
	Complex c1(1, 2), c2(3, 4);


	1	全局函数法 实现 + 运算符重载
	 Complex operator+(Complex &c1, Complex &c2);
	//Complex c3 = c1 + c2;
	//c3.printCom();

	2 成员函数 法 实现 -运算符重载
	c1.operator-(c2);
	Complex operator-(Complex &c2)
	//Complex c4 = c1 - c2;
	//c4.printCom();

	前置++操作符 用全局函数实现
	//++c1;
	//c1.printCom();

	前置--操作符 成员函数方法
	//--c1;
	//c1.printCom();
	Complex& operator++(Complex &c1)
	c1.operator--();

	后置++操作符 用全局函数实现
	//c1++;
	//c1.printCom();

	//后置--操作符 用成员函数实现
	Complex c = c1--;
	//重载后置--操作符 相当于函数调用 传到调用的函数中,this指针对c1的内存进行了-1操作 但是返回出来的东西跟c1没有关系
	//返回出来的是tmp的临时对象 也就是c1的前一时刻的状态
	c.printCom();//c1未-1时刻的状态
	c1.printCom();
	//c1.operator--()

	cout << "hello..." << endl;
	system("pause");
	return;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值