使用非成员函数(non-member)处理函数的所有参数都需要类型转换
本文地址: http://blog.csdn.net/caroline_wendy/article/details/24309293
有些函数, 所有参数都需要使用类型转换, 比如乘法, 写一个有理数类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