C++中的operator,有两种用法,一种是operator overloading(操作符重载),一种是operator casting(操作隐式转换)。下面分别进行介绍:
1.operator overloading
C++可能通过operator 重载操作符,格式如下:类型T operator 操作符 (),如比重载+,如下所示
template<typename T> class A {
public:
const T operator + (const T& rhs) {
return this->m_ + rhs; }
private:
T m_;
};
又比如STL中的函数对象,重载(),如下所示
template<typename T> struct A {
T operator()(const T& lhs, const T& rhs)
{ return lhs-rhs;}
};
2 operator casting
C++可能通过operator 重载隐式转换,格式如下: operator 类型T (),如下所示
class A {
public:
operator B* () { return this->b_;}
operator const B* () {return this->b_;}
operator B& () {return *this->b_;}
private:
B* b_;
};
A a;
当if(a),编译时,其中它转换成if(a.operator B*()),其实也就是判断 if(a.b_)