版本一

  1. #include<iostream>
  2. using namespace std;
  3. class Rational {
  4. public:
  5. Rational(int a = 0,int b = 1) : a(a),b(b) {}
  6. const Rational operator*(const Rational& rhs) const {
  7. return Rational(a * rhs.a,b * rhs.b);
  8. }
  9. private:
  10. int a;
  11. int b;
  12. };
  13. int main() {
  14. Rational r1(1,8);
  15. Rational r2(1,2);
  16. Rational r3 = r1 * r2;
  17. Rational r4 = 3 * r1;
  18. Rational r5 = r1 * 3;
  19. return 0;
  20. }

第17行报错

  1. Rational r4 = 3.operator*(r1); //3没有成员函数operator*
  2. Rational r5 = r1.operator*(3);

如果设计一个在namespace里或全局作用域里的operator*,也会因为参数不匹配而报错
可是为什么18行不报错?

  1. 等同于
  2. const Rational temp(3);
  3. Rational r5 = r1.operator*(temp);

版本二 一致性

如果把构造函数设置为explicit,就不支持隐式转换,那么16行17行就达到了一致性,但是不支持混合式运算

版本三 支持混合运算 且有 一致性

非成员函数,friend能避免就要避免

  1. const Rational operator*(const Rational& lhs,const Rational& rhs) {
  2. return Rational(lhs.getA() * rhs.getA(),lhs.getB() * rhs.getB());
  3. }

总结

如果需要对函数所有参数都要做隐式转换,那么这个函数必须是非成员函数(friend也不可以)