c++重载自增和自减操作符

本文介绍了一个自定义类Pair,该类重载了前置和后置自增操作符。通过具体的代码示例展示了如何使用这些重载的操作符来改变Pair对象中的整型成员变量。

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

#include<iostream>
#include<cstdlib>

using namespace std;

class Pair{
public:
	Pair(int firstPart, int secondPart);
	Pair operator++();
	Pair operator++(int);
	void setFirstPart(int firstPart);
	void setSecondPart(int secondPart);
	int getFirstPart() const; 
	int getSecondPart() const;
	
private:
	int firstPart;
	int secondPart;
};

int main(){
	Pair a(1, 2);
	cout<<"Postfix a++:";
	cout<<a.getFirstPart()<<" "<<a.getSecondPart()<<endl;
	Pair b = a++;
	cout<<"Postfix b++:";
	cout<<b.getFirstPart()<<" "<<b.getSecondPart()<<endl;
	cout<<a.getFirstPart()<<" "<<a.getSecondPart()<<endl;
	
	a = Pair(1, 2);
	cout<<"Prefix ++a:";
	cout<<a.getFirstPart()<<" "<<a.getSecondPart()<<endl;
	Pair c = ++a;
	cout<<"Postfix c++:";
	cout<<c.getFirstPart()<<" "<<c.getSecondPart()<<endl;
	cout<<a.getFirstPart()<<" "<<a.getSecondPart()<<endl;
}

Pair::Pair(int firstPart, int secondPart):firstPart(firstPart),secondPart(secondPart){
	
}
Pair Pair::operator++(){
	firstPart++;
	secondPart++;
	return Pair(firstPart, secondPart);
}

Pair Pair::operator++(int flag){
	int temp1 = firstPart;
	int temp2 = secondPart;
	firstPart++;
	secondPart++;
	return Pair(temp1, temp2);
}

int Pair::getFirstPart() const{
	return firstPart;
}

int Pair::getSecondPart() const{
	return secondPart;
}

void Pair::setFirstPart(int firstPart){
	this->firstPart= firstPart;
}

void Pair::setSecondPart(int secondPart){
	this->secondPart = secondPart;
}
上面是重载自增操作符的代码,自减操作符类似。注意:在后缀自增的重载函数里面的一个int类型的参数只是作为编译器的一个标志,在函数中并没有用到。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值