本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
经验:如果你需要为某个函数的所有参数(包括被this指针所指的那个隐喻函数)进行类型转换,那么这个函数必须是个non-member
示例:operator *是member函数的情况
#include <iostream>
#include <string>
using namespace std;
class Rational{
public:
Rational(int nn = 0, int dd = 1): n(n), d(dd){}
const Rational operator* (const Rational &rhs) const{return Rational(n * rhs.n, d * rhs.d);};
int numerator() const{return n;}
int denominator() const {return d;}
private:
int n, d;
};
int main(){
Rational oneHalf(1, 2);
Rational result;
result = oneHalf * 2; // ok
result = 2 * oneHalf; // error C2677: 二进制“*”: 没有找到接受“Rational”类型的全局运算符(或没有可接受的转换)
system("pause");
}
解析:
result= oneHalf * 2 等价于 result = oneHalf.operator*(2); 而int类型的2会被隐式类型转换为Rational类型
result= 2 * oneHalf 等价于 result = 2.operator*(oneHalf); 而int类型的并没有相应的class,也就没有operator*函数
纠正:让operator*成为non-member函数
#include <iostream>
#include <string>
using namespace std;
class Rational{
public:
Rational(int nn = 0, int dd = 1): n(n), d(dd){}
int numerator() const{return n;}
int denominator() const {return d;}
private:
int n, d;
};
const Rational operator* (const Rational &lhr, const Rational &rhs)
{
return Rational(lhr.numerator() * rhs.numerator(), lhr.numerator() * rhs.denominator());
};
int main(){
Rational oneHalf(1, 2);
Rational result;
result = oneHalf * 2;
result = 2 * oneHalf;
system("pause");
}