C++_notes5 Posted on 2020-05-11 | In C++ **侯捷老师的C++笔记5** #### p2. `Conversion function`, 转换函数 12345678910111213141516171819202122232425262728293031class 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转换成fractionFraction d = 4 + f; // no error, can only use 可以调用double