C++_notes5

**侯捷老师的C++笔记5**
#### p2. `Conversion function`, 转换函数
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
class Fraction
{
public:
// non-explicit-one-argument-ctor
Fraction (int num, int den = 1)
: m_numerator (num), m_denominator (den) { }

// explicit-one-argument-ctor
explicit Fraction (int num, int dne = 1)
: m_numerator (num), m_denominator (den) {}


// 将Fraction直接转成double类型,不用写返回类型
// double d = 4 + f;
operator double() const {
return (double) m_numerator / m_denominator;
}
// 定义Fraction的+
// Fraction d2 = f + 4; 4必须在右边
Fraction operator + (const Fraction& f) {
return Fraction(...);
}
private:
int m_numerator; // 分子
int m_denominator; // 分母
};

Fraction f (3, 5);
Fraction d = f + 4; //Error, ambiguous
// 可以调用double(), d可以转换成fraction,也可以调用operator+,4转换成fraction
Fraction d = 4 + f; // no error, can only use 可以调用double
0%