超载的减法运算符(-)也很简单:
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,仙)。因此,每当我们过载对不同类型的操作数的二元操作符,我们真的需要写两个功能-一个用于每个案例。这里是一个例子: