运算符重载之前置自增运算符和后置自增运算符

本文介绍了C++中自增运算符的重载方法,包括前置自增和后置自增的区别,并通过一个复数类的例子展示了如何实现这两种自增运算符。

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

运算符重载是C++多态性的一种体现,运算符的重载对像C++这类面向对象的编程语言编程很有帮助。

今天这里介绍运算符重载里的自增运算符。

我们都知道自增运算符++有两种,一个是前置,一个后置,至于它们什么区别这里不赘述。

那么我们应该如何重置前置自增运算符和后置自增运算符呢?

[返回类型] operator++() ;    //如果参数列表里什么都没有,那么就是重载前置自增运算符

[返回类型] operator++(int) ;    /*如果参数列表里有一个参数,不管是什么类型,那么就是重载后置自增运算符,这个类型是int,double或者是其他都无所谓,它的目的仅仅是告诉编译器这里是有参数的,如果有参数,编译器就知道这里是重载后置运算符。*/

下面是我写的编程例子,注释不多,就是定义一个复数的类型,里面重载了+和前置自增和后置自增。

#include<iostream>
using namespace std;
class complex
{
	private:
		double real,img;
	public:
		complex(double x=0.0,double y=0.0):real(x),img(y){  }
		virtual ~complex(){  }
		
		double read_real()
		{
			return real;
		}
		
		double read_img()
		{
			return img;
		}
		
		void set_real(double t)
		{
			real=t;
		}
		
		void set_img(double t)
		{
			img=t;
		}
		
		complex operator+(const complex& one)
		{
			complex result(this->real+one.real,this->img+one.img);
			return result;
		}
		
		complex operator++()     //前置自增运算符 
		{
			complex result;
			this->real++;
			this->img++;
			result.set_real(this->real);
			result.set_img(this->img);   //自增完才赋值
			
			return result; 
		}
		
		complex operator++(int)     //后置自增运算符 
		{
			complex result;
			result.set_real(this->real);
			result.set_img(this->img);   //先赋值再自增
			this->real++;
			this->img++;
			
			return result; 
		}
};


int main()
{
	complex a(3.2,4.5),b(1.1,2.4);
	cout<<"a:"<<a.read_real()<<"+"<<a.read_img()<<"i\n";
	cout<<"b:"<<b.read_real()<<"+"<<b.read_img()<<"i\n";
	
	complex c=a+b;
	cout<<"c:"<<c.read_real()<<"+"<<c.read_img()<<"i\n";
	
	cout<<"\n\n下面展示前置自增运算符:\n"; 
	a=++c;
	cout<<"a:"<<a.read_real()<<"+"<<a.read_img()<<"i\n";
	cout<<"c:"<<c.read_real()<<"+"<<c.read_img()<<"i\n";
	
	cout<<"\n\n下面展示后置自增运算符:\n"; 
	a=c++;
	cout<<"a:"<<a.read_real()<<"+"<<a.read_img()<<"i\n";
	cout<<"c:"<<c.read_real()<<"+"<<c.read_img()<<"i\n";
	
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值