#include <iostream>
class Cents
{
private:
int m_cents;
public:
Cents(int cents) { m_cents = cents; }
// add Cents + Cents using a friend function
friend Cents operator+(const Cents &c1, const Cents &c2);
// subtract Cents - Cents using a friend function
friend Cents operator-(const Cents &c1, const Cents &c2);
int getCents() const { return m_cents; }
};
// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2)
{
// use the Cents constructor and operator+(int, int)
// we can access m_cents directly because this is a friend function
return Cents(c1.m_cents + c2.m_cents);
}
// note: this function is not a member function!
Cents operator-(const Cents &c1, const Cents &c2)
{
// use the Cents constructor and operator-(int, int)
// we can access m_cents directly because this is a friend function
return Cents(c1.m_cents - c2.m_cents);
}
int main()
{
Cents cents1(6);
Cents cents2(2);
Cents centsSum = cents1 - cents2;
std::cout << "I have " << centsSum.getCents() << " cents." << std::endl;
return 0;
}我们一般不推荐这个,因为不平凡的成员函数的定义是更好的保存在一个单独的.cpp文件,在类定义之外。然而,我们将在未来的教程中使用这种模式,以保持例子简洁。
不同类型的操作数的重载操作符
通常情况下,你希望你的重载操作符与不同类型的操作数一起工作。例如,如果我们有美分(4),我们可能要添加整数6到这个产生的结果美分(10)。
当C++表达式求值x + y,x和y是第一个参数,成为第二参数。当X和Y有相同的类型,它并不重要,如果你添加X + Y或Y + X -无论哪种方式,相同的版本的运营商+被称为。然而,当操作数有不同的类型时,X + Y是不相同的Y + x。
例如,仙(4)+ 6会调用操作符+(美分,int),和6美分(4)会调用操作符+(int,美分)。因此,当我们重载了不同类型的操作数的二进制操作符时,我们实际上需要写两个函数--一个用于每个情况。这里是一个例子:
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
class Cents
{
private:
int m_cents;
public:
Cents(int cents) { m_cents = cents; }
// add Cents + int using a friend function
friend Cents operator+(const Cents &c1, int value);
// add int + Cents using a friend function
friend Cents operator+(int value, const Cents &c1);
int GetCents() { return m_cents; }
};
// note: this function is not a member function!
Cents operator+(const Cents &c1, int value)
{
// use the Cents constructor and operator+(int, int)
// we can access m_cents directly because this is a friend function
return Cents(c1.m_cents + value);
}
// note: this function is not a member function!
Cents operator+(int value, const Cents &c1)
{
// use the Cents constructor and operator+(int, int)
// we can access m_cents directly because this is a friend function
return Cents(c1.m_cents + value);
}
int main()
{
Cents c1 = Cents(4) + 6;
Cents c2 = 6 + Cents(4);
std::cout << "I have " << c1.getCents() << " cents." << std::endl;
std::cout << "I have " << c2.getCents() << " cents." << std::endl;
return 0;
376

被折叠的 条评论
为什么被折叠?



