c++重载自增与自减运算符(前置与后置)

运算符重载

要点:
1. 后置的运算符要带一个整型参数(用来与前置运算符区分开)。
2.后置的返回值不要用引用(否则会因为是局部变量导致返回为一个不存在的值)。
3.再在置中要定义一个临时变量来返回之前的值。
4.在后置运算符中可以使用前置运算符来简化。

代码(内有详解)

#include <iostream>
using namespace std;

class point {
	public:
		point(int x1 = 0, int y1 = 0) {//构造函数,带默认参数
			x = x1;
			y = y1;
		}

		int getx() {
			return x;
		}
		int gety() {
			return y;
		}

		void show() {//用来及时输出值
			cout << x << "," << y;
		}
		point &operator ++();//重载的运算符
		point operator ++(int x);
		point &operator --();
		point  operator --(int x);
	private:
		int x;
		int y;

};

point &point:: operator ++() {
	this->x++;
	this->y++;
	return *this;
}

point  point::operator ++(int x ) {
	point p(*this);//定义一个临时的类来保存加之前的值
	++(*this);//利用了重载的前置运算符
	return p;
}

point &point:: operator --() {
	this->x--;
	this->y--;
	return *this;
}

point  point::operator --(int x ) {
	point p(*this);
	--(*this);
	return p;
}

int main() {
	int x, y;
	cin >> x >> y;
	point p(x, y);
	cout << "(" << p.getx() << "," << p.gety() << ")" << endl;
	cout << "(" ;
	p++.show();
	cout << ")" << endl;
	cout << "(" ;
	(++p).show() ;
	cout << ")" << endl;
	cout << "(" ;
	p--.show() ;
	cout << ")" << endl;
	cout << "(" ;
	(--p).show() ;//前置必须要加小括号
	cout << ")" << endl;
	return 0;
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落春只在无意间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值