C++網易雲課堂開發工程師--轉換函數

class Fraction{函數

  public:spa

    Fraction(int num, int den = 1) : m_numerator(num), m_denominator(den) { }ci

    Fraction operator + (const Fraction& f){it

    return Fraction(.....);io

    }
class

  private:構造函數

    int m_numerator;類型轉換

    int m_denominator;co

}block

Fraction f(3, 5);

Fraction d2 = f + 4;  //調用non-explicit ctor 將4轉爲Fraction,這部份內容挺有趣的!

explicit-one-argument ctor

  explicit不容許自動類型轉換,一般用在構造函數前面(90%)。

class Fraction{

  public:

    explict Fraction(int num, int den = 1) : m_numberator(num), m_denominator(den) {  }

    operator double( ) const {return (double)(m_numerator / m_denominator)}

    Fraction operator (const Fraction& f)  { return Fraction(...) };

  private:

    int m_numerator;

    int m_denominator;

};

Fraction f(3, 5);

Fraction d2 = f + 4;  //不容許自動類型轉換

相關文章
相關標籤/搜索