单目运算符前++与后++的重载

本文介绍C++中单目运算符++的重载方法,包括前缀++和后缀++的不同实现方式,并通过具体示例展示了如何在自定义类中正确使用这两种运算符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单目运算符前++与后++的重载

#include "stdafx.h"
#include <iostream>
using namespace std;

//重载前++ 与 后++

//返回对象和引用:优先考虑返回引用 
//返回类型加不加const:优先考虑加const类型

//运算符重载 按照基础数据类型的用法

class Complex
{
public:
	Complex(float x = 0, float y = 0)
		:_x(x), _y(y){}
	void dis()
	{
		cout << "(" << _x << "," << _y << ")" << endl;
	}

	Complex& operator++(); //前++
	const Complex operator++(int); //这个int为哑元 只是为了作区分用的

private:
	float _x;
	float _y;
};


Complex& Complex::operator++() //前++
{
	this->_x++;
	this->_y++;
	return *this;
}


//const对象不能调用非const成员函数 所以此处加const 可以满足a++++;不成立的条件
const Complex Complex::operator++(int)
{
	Complex t(this->_x, this->_y); //先返回一个替身(没进行++运算的) 符合逻辑

	this->_x++;
	this->_y++;

	return t; //此处返回的替身是局部变量,所以返回类型不能&,只能是对象
}


int _tmain(int argc, _TCHAR* argv[])
{
	//测试前++的性质
	int a = 100;
	int b = ++a;
	cout << a << " " << b << endl;
	++++++++a;
	cout << a << endl;

	cout << "==================" << endl;

	Complex c(1, 2);
	Complex c2 = ++++c;
	c2.dis();

	cout << "==================" << endl;

	//测试后++的性质
	int p = 100;
	int q = a++;
	//a++++;  语法不通过

	cout << "==================" << endl;

	Complex c3(1, 2);
	Complex c4 = c3++;
	c3.dis();
	c4.dis();

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值