转换函数
1 2 3 4 5 6 7 8 9 10
| class Fraction { public: Fraction(int num, int den=1): m_numerator(num), m_denominator(den) {} operator double() const { return (double) (m_numerator / m_denominator); } private: int m_numerator; int m_denominator; }
|
如何调用:
1 2
| Fraction f(3,5); double d = 4+f;
|
non-explicit-one-argument ctor
1 2 3 4 5 6 7 8 9 10
| class Fraction { public: Fraction(int num, int den=1): m_numerator(num), m_denominator(den) {} Fraction operator + (const Fraction& f) { return (double) (m_numerator / m_denominator); } private: int m_numerator; int m_denominator; }
|
调用:
1 2
| Fraction f(3,5); double d = 4+f;
|
上面的operator +
和double
两个函数不能同时存在,若同时存在编译器会报错
explicit-构造函数
1 2 3 4 5 6 7 8 9 10
| class Fraction { public: explicit Fraction(int num, int den=1): m_numerator(num), m_denominator(den) {} Fraction operator + (const Fraction& f) { return (double) (m_numerator / m_denominator); } private: int m_numerator; int m_denominator; }
|
智能指针
TODO