c++重载单目运算符

所谓单目运算符,是指运算的对象或者变量只有一个。比如:

a++;
b--;

在c++语言中,当参加运算的是对象时,需要使用重载单目运算符函数。

首先给出类的定义:

class FeetInches 
{ 
private: 
     int  feet, inches;
public:
	void display()
	{
		cout<<feet<<"."<<inches<<endl;
	}
	FeetInches(int f,int i)
	{
		feet=f;
		inches=i;
	}
    FeetInches   operator++();       //重载前置++运算符
    FeetInches   operator++( int );  //重载后置++运算符,注意到括号里面有一个哑元。这是区分前后置的关键
};

接下来编写函数:

前置++是先加后用

FeetInches   FeetInches::operator++(  )
{
    ++inches;
    return  *this;
}                         //前置++比较简单,直接返回*this即可

后置++是先用后加,所以编写上与前置++有所区别:

FeetInches FeetInches::operator++(int)
{
	FeetInches temp(feet, inches);       //定义一个temp变量,用当前对象来初始化它。
    inches++;                           //执行++操作。
    return temp;                          //因为是先使用后加,所以返回改变之前的值,此时当前变量已经改变。
 }

以上就是++运算符的重载,类比可写出--运算符重载。

完整代码:

#include<iostream>
using namespace std;
class FeetInches 
{ 
private: 
     int  feet, inches;
public:
	void display()
	{
		cout<<feet<<"."<<inches<<endl;
	}
	FeetInches(int f,int i)
	{
		feet=f;
		inches=i;
	}
    FeetInches   operator++(  );
    FeetInches   operator++( int );
};
FeetInches   FeetInches::operator++(  )
{
    ++inches;
    return  *this;
}
FeetInches FeetInches::operator++(int)
{
	FeetInches temp(feet, inches);
    inches++;
    return temp;
 }
int main()
{
	FeetInches f1(1,3),f2(2,4),f3(0,0),f4(0,0);
	f3=f1++;
	f4=++f2;
	f1.display();
	f2.display();
	f3.display();
	f4.display();
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Math-L

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

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

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

打赏作者

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

抵扣说明:

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

余额充值