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
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
// Overload cCents + int
friend Cents operator+(const Cents &cCents, int nCents);
// Overload int + cCents
friend Cents operator+(int nCents, const Cents &cCents);
int GetCents() { return m_nCents; }
};
// note: this function is not a member function!
Cents operator+(const Cents &cCents, int nCents)
{
return Cents(cCents.m_nCents + nCents);
}
// note: this function is not a member function!
Cents operator+(int nCents, const Cents &cCents)
{
return Cents(cCents.m_nCents + nCents);
}
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;
}
需要注意的是重载函数具有相同的实现,是因为他们做同样的事情,他们只是把他们的参数以不同的顺序。
另一个例子
让我们看另外一个例子:
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class MinMax
{
private:
int m_nMin; // The min value seen so far
int m_nMax; // The max value seen so far
public:
MinMax(int nMin, int nMax)
{
m_nMin = nMin;
m_nMax = nMax;
}
int GetMin() { return m_nMin; }
int GetMax() { return m_nMax; }
friend MinMax operator+(const MinMax &cM1, const MinMax &cM2);
friend MinMax operator+(const MinMax &cM, int nValue);
friend MinMax operator+(int nValue, const MinMax &cM);
};
MinMax operator+(const MinMax &cM1, const MinMax &cM2)
{
// Get the minimum value seen in cM1 and cM2
int nMin = cM1.m_nMin < cM2.m_nMin ? cM1.m_nMin : cM2.m_nMin;
// Get the maximum value seen in cM1 and cM2
int nMax = cM1.m_nMax > cM2.m_nMax ? cM1.m_nMax : cM2.m_nMax;
return MinMax(nMin, nMax);
}
MinMax operator+(const MinMax &cM, int nValue)
{
// Get the minimum value seen in cM and nValue
int nMin = cM.m_nMin < nValue ? cM.m_nMin : nValue;
// Get the maximum value seen in cM and nValue
int nMax = cM.m_nMax > nValue ? cM.m_nMax : nValue;
return MinMax(nMin, nMax);
}
MinMax operator+(int nValue, const MinMax &cM)
{
// call operator+(MinMax, nValue)
return (cM + nValue);
}
int main()
{
MinMax cM1(10, 15);
MinMax cM2(8, 11);
MinMax cM3(3, 12);
MinMax cMFinal = cM1 + cM2 + 5 + 8 + cM3 + 16;
std::cout << "Result: (" << cMFinal.GetMin() << ", " <<
cMFinal.GetMax() << ")" << std::endl;
return 0;
}