class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
// Overload -cCents
friend Cents operator-(const Cents &cCents);
};
// note: this function is not a member function!
Cents operator-(const Cents &cCents)
{
return Cents(-cCents.m_nCents);
}你会注意到,这种方法是非常相似的。然而,成员函数版本的操作不需要任何参数!参数去哪里?在课上隐藏的this指针,你得知一个成员函数的隐式*这个指针总是指向类对象的成员函数是工作。我们不得不在朋友的功能版本明确列出的参数(即没有这个指针)成为隐*这个参数在成员函数版本。
记住,当C++看到函数原型美分::操作符();,编译器内部转换此算子(const美分美分这个),你会注意到我们的朋友版美分算子是几乎相同的-(const美分&;ccents)!
超载的二进制加法(+)算子
让我们来看看一个二进制运算符的一个示例一看超载的两种方式。首先,重载操作符+使用友元函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
// Overload cCents + int
Cents operator+(int nCents);
int GetCents() { return m_nCents; }
};
// note: this function is a member function!
Cents Cents::operator+(int nCents)
{
return Cents(m_nCents + nCents);
}

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



