用一个例子来理解c++中的重载

格式:operatorop(argument-list)

例:operator+(),表明重载“+”运算符,其中op必须为C++运算符,如@不是c++中的符号,则不能定义为重载。

下面用两个时间的类对象来说明重载“+”运算符:

class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m);
~Time();
void addMin(int m);
void addHou(int h);
//Time sumTime(const Time & t)const;
Time operator+(const Time & t)const;//重载+运算符,其实就是把类成员函数名sumTime换成operator+来完成相同的功能
void showTime()const;
};


Time::Time()
{
hours = minutes = 0;
}
Time::Time(int h, int m)
{
hours = h;
minutes = m;
}
Time::~Time()
{
	;
}
void Time::addMin(int m)
{
hours = hours + m / 60;
minutes = (m + minutes) % 60;
}
void Time::addHou(int h)
{
hours = hours + h;
}
//Time Time::sumTime(const Time & t)const
//Time Time::operator+(const Time & t)const//同样在函数定义处也要换成operator+
{
Time sum;

sum.minutes = t.minutes + minutes;
sum.hours = t.hours + hours + sum.minutes/60;
sum.minutes %= 60;
return sum;
}
void Time::showTime()const
{
std::cout << hours << ":" << minutes << std::endl;
}


int main()
{
using std::cout;
using std::endl;
Time planning;
Time colding(2, 56);
Time fixing(11, 36);
Time total;

cout << "planning time:"  ;
planning.showTime();
cout << endl;

cout << "colding time:";
colding.showTime();
cout << endl;

cout << "fixing time:";
fixing.showTime();
cout << endl;

total = colding.sumTime(fixing);
total= colding + fixing;//完成相同的功能
cout << "colding.sumTime(fixing):";
total.showTime();
cout << endl;

system("pause");
return 0;
}


必须要注意的是重载后的运算符必须至少有一个操作数是用户定义的类型,如上使用+运算符时,必须要含有Time类类型的对象。

并非每个运算符都能重载,如sizeof运算符、成员运算符“·”等都不能重载,此处不细说

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值