operator它有两种用法,一种是operator overloading(操作符重载),一种是operator casting(操作隐式转换)。
1、操作符重载
C++可以通过operator实现重载操作符,格式如下:类型T operator 操作符 (),比如重载+, 
template<typename T> class A
{
public:
     const T operator+(const T& rhs)
     {
         return this->m_ + rhs;
     }
private:
     T m_;
};

 

 
 
 
 
2、 操作隐式转换
C++可以通过operator实现重载隐式转换,格式如下: operator T (),其中T是一个类型,比如下面这个例子

class A
{
public:
    explicit A(int b=0){
        b_=b;
    }
    operator   int() { return this->b_; } 
 
private:
    int b_;
};
 
int main()  
{ 
    A a;
    int b=a;
    cout<<b;
    return 0;  
}
当执行b=a时a就发生了隐式类型转换,实际上执行了a.opertor int()函数 即
int b=a相当于 int b=a.b_

 

相关文章:

  • 2022-12-23
  • 2021-12-20
  • 2022-02-28
  • 2021-05-18
  • 2022-12-23
  • 2021-09-10
  • 2021-09-07
  • 2021-12-25
猜你喜欢
  • 2022-12-23
  • 2021-07-28
相关资源
相似解决方案