C++中 当函数所有参数都需要类型转换时 需要将其声明为non-member函数

考虑下面的一段代码:

 1 #ifndef RATIONAL_H
 2 #define RATIONAL_H
 3 #include<iostream>
 4 using namespace std;
 5 
 6 class Rational
 7 {
 8 public:
 9     Rational(int nn = 1, int dd = 0)
10     {
11         n = nn;
12         d = dd;
13     }
14     void print()
15     {
16         cout<<this->n<<" "<<this-d<<endl;
17     }
18     const Rational operator*(const Rational& r2) const
19     {
20         Rational result(this->n*r2.n, this->d*r2.d);
21         return  result;
22     }
23 
24 private:
25     int n;
26     int d;
27 };
28 
29 #endif
30 
31 #include "stdafx.h"
32 #include "Rational.h"
33 
34 int _tmain(int argc, _TCHAR* argv[])
35 {
36     Rational r1(3,2);
37     Rational r = 2*r1;
38 
39     r.print();
40 
41     system("pause");
42 
43     return 0;
44 }
View Code

上面的代码不会通过编译,Rational r = 2*r1;这一行会出现错误: 二进制“*”: 没有找到接受“Rational”类型的全局运算符(或没有可接受的转换) 。但是如果改为:Rational r = r1*2,则没有问题,其相当于第一次的*找不到合适的函数,第二次的*则默认调用类的成员函数operator*,而参数2则被隐式转换为Rational对象。为了解决这个问题,即使得operator*可以支持混合式运算,且满足我们所熟知的乘法的交换律,就需要将operator*改为非成员函数:

即定义在类的外部,函数定义如下:

1 const Rational operator*(const Rational& r1, const Rational& r2)
2 {
3     Rational result(r1.n*r2.n, r1.d*r2.d);
4     return result;
5 }
View Code

 

以上来自Effective C++中文版第三版case24.

posted on 2013-05-27 10:22  Sophia-呵呵小猪  阅读(273)  评论(0编辑  收藏  举报