C++中关于重载运算符

相信很多朋友和我一样一开始看的时候很不理解

对*的重载(类内定义)

CMyTime CMyTime::operator*(double n) const                 //重载为乘法运算符函数。
{
CMyTime result;
long totalMinutes = m_hours * 60 * n+ m_minutes *n;
result.m_minutes = totalMinutes % 60;
result.m_hours = totalMinutes / 60;
return result;
}

然后有这句

adjusted = total *1.5;

看作是

adjusted = total.operator*(1.5)

就比较容易理解了,也因此很容看出此时调换total和1.5的顺序是不可以的,1.5本身是个常量,不是类类型更没有成员函数了。

同理,在类外定义

Box operator+(const Box& a, const Box& b)
{
    Box box;
    box.length = a.length + b.length;
    box.breadth = a.breadth + b.breadth;
    box.height = a.height + b.height;
    // cout << box.length << "--" << box.breadth << "--" << box.height << endl; 
    return box;
}
Box3 = Box1 + Box2;.
Box3 = operator*(Box1,Box2);

目前不知道有没有三元运算符。。。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值