有些函數, 所有參數都需要使用類型轉換, 比如乘法, 寫一個有理數類Rational, 需要執行乘法操作:
函數滿足: Rational = Rational*double; Rational = double*Rational; 則需要使用非成員函數(non-member);
成員函數的發起者必須是類, 因為可能出現double類型在前的情況, 則無法執行乘法, 所以應使用非成員函數;
執行時: 即Rational = Rational*Rational(double); Rational = Rational(double)*Rational, 發生了隱式轉換.
代碼:
/* * test.cpp * * Created on: 2014.04.22 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> //有理數 class Rational { public: Rational(double numerator = 0, double denominator = 1) : m_n(numerator), m_d(denominator) {} double numerator() const {return m_n;}; double denominator() const {return m_d;}; double value() {return (m_n/m_d);} private: double m_n; double m_d; }; const Rational operator* (const Rational& lhs, const Rational& rhs) { return Rational(lhs.numerator()*rhs.numerator(), lhs.denominator()*rhs.denominator()); } int main(void) { Rational oneFourth(1, 4); Rational result; result = oneFourth * 3.5; result = 3.5 * oneFourth; std::cout << "result = " << result.value() << std::endl; return 0; }
輸出:
result = 0.875
作者:csdn部落格 Spike_King
更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/