多态性之运算符重载(二)

运算符重载包括重载为类的成员函数和重载为友元函数。

这里要特别注意的就是单目运算符的前置、后置时的运算符重载规则。

下面是简单的说明性代码,++,--(前置和后置)重载为类的成员函数和类的友元函数时的情形

#include<iostream>
using namespace std;
class Time
{
public:
	Time(int h=0,int m=0)
	{
		H=h;
		M=m;
	}
	void showtime();
	Time operator ++();//前置运算符++(类的成员函数)
	Time operator ++(int);//后置运算符++(类的成员函数)
	friend Time operator --(Time & oper);//重载为类的友元函数
	friend Time operator --(Time & oper,int);///重载为类的友元函数
private:
	int H,M;
};
void Time::showtime()
{
	cout<<"hour="<<H<<"minute="<<M<<endl;
}
Time Time::operator++()
{
	M++;
	H++;
	return *this;//返回当前的操作对象	
}
Time Time::operator++(int)
{
	
	//Time old=*this;
	//++(*this);
	//return old;
	return Time(H++,M++);//创建临时我一个无名对象作为返回值
}
Time operator --(Time & oper)
{
	return Time(--oper.H,--oper.M);

}
Time operator --(Time & oper,int)
{
	return Time(oper.H--,oper.M--);
}
int main()
{
	Time t1(10,22);
	t1.showtime();
	cout<<"------------------运算符重载为类的成员函数---------------"<<endl;
	cout<<"使用前置运算符的++"<<endl;
	(++t1).showtime();
	t1.showtime();
	cout<<"使用后置运算符的++"<<endl;
	(t1++).showtime();
	t1.showtime();
	cout<<"----------------------------------------------------------"<<endl;
	cout<<"------------------运算符重载为类的友元函数---------------"<<endl;
	cout<<"使用前置运算符--"<<endl;
	(--t1).showtime();
	t1.showtime();
	cout<<"使用后置运算符"<<endl;
	(t1--).showtime();
	t1.showtime();

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值