C++ 前缀++后 缀++重载的写法

C++ 前缀++后 缀++重载的写法:

#include<iostream>
using namespace std;

class Complex
{
private:
	int i_r;
	int i_v;
public:
	friend 	ostream& operator<<(ostream &cout,Complex &cp);
	Complex(int i_r = 0,int i_v = 0)
	{
		this->i_r = i_r;
		this->i_v = i_v;
	}
	~Complex()
	{
	}
	Complex &operator++()//前缀++重载 返回的是引用
	{
		this->i_r++;
		this->i_v++;
		return *this;
	}
	Complex operator++(int)// 后缀++ 重载写法 (int) 区分前缀的必须写成int 返回是匿名对象
	{
		Complex temp=*this;
		this->i_r++;
		this->i_v++;
		return temp;
	}

};

ostream& operator<<(ostream &cout,Complex &cp)// 重载<<
{
	cout<<cp.i_r<<"+"<<cp.i_v<<"i"<<endl;
	return cout;
}


void main()
{
	Complex cp(1,2);
	cout<<cp<<endl;
	cout<<++cp<<endl;
	cout<<cp++<<endl;
	system("pause");
}

由于operator++ 分前缀和后缀,C++编译器为了区分使用operator++(int)表示后缀 这里int 不具有传参功能,只是相当于一个标识。只能是int否则编译器会报错。


  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值