作数的类型

本文详细介绍了C++中运算符重载的概念、规则以及如何实现加法、减法、乘法和除法运算符重载。着重解释了不同操作数类型之间的区别,并提供了实例代码来演示不同情况下的操作符重载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

超载的减法运算符-)也很简单
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    // overload Cents + Cents
    friend Cents operator+(const Cents &c1, const Cents &c2);
 
    // overload Cents - Cents
    friend Cents operator-(const Cents &c1, const Cents &c2);
 
    int GetCents() { return m_nCents; }
};
 
// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2)
{
    // use the Cents constructor and operator+(int, int)
    return Cents(c1.m_nCents + c2.m_nCents);
}
 
// note: this function is not a member function!
Cents operator-(const Cents &c1, const Cents &c2)
{
    // use the Cents constructor and operator-(int, int)
    return Cents(c1.m_nCents - c2.m_nCents);
}

重载乘法操作符(*)和除法运算符(/)被定义为算子和算子/功能一样简单。

重载运算符的操作数的类型

经常的情况是,你想要你的重载操作符的操作数是与不同类型的工作。例如,如果我们有仙(4),我们可能要添加整数6到这来产生结果美分(10)。

当C++计算表达式x + y,x和y是第一个参数,成为第二个参数。当X和Y具有相同的类型,它不如果你加X + Y或y + x -无论是物质,运算符+相同的版本被称为。然而,当操作数具有不同的类型,x + y y + X是不相同的

例如,仙(4)+ 6将调用操作符+(美分,int),和6美分(4)将调用操作符+(int,仙)。因此,每当我们过载对不同类型的操作数的二元操作符,我们真的需要写两个功能-一个用于每个案例。这里是一个例子:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值