C++技巧之operator操做符

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中的函数对象,重载(),这是C++中较推荐的写法,功能与函数指针相似,以下所示

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* () const {return this->b_;}    
   operator B& () { return *this->b_;}
   operator const B& () const {return *this->b_;} 

private:
   B* b_;
};
A a;
当if(a),编译时,其中它转换成if(a.operator B*()),其实也就是判断 if(a.b_)

============================================================= 函数

class test{ this

public:
     int v;
   /*构造函数*/
     test():v(0){}
     test(const int &a):v(a){}
     test(const test &t1):v(t1.v){} 
    
   /*如下重载小于号 < */
     //比较两个对象的大小 
     bool operator<(const test &t1) const{ 
         return (v < t1.v);
     }
     //比较对象和int的大小 
     bool operator<(const int &t1) const{ 
         return (v < t1);
     }
     //友元函数,比较int和对象的大小 
     friend inline bool operator<(const int &a, const test & t1){
         return (a < t1.v);
     }
    
   /*如下重载赋值号 = */
     //对象间赋值 
     test & operator=(const test &t1){
         v = t1.v;
         return *this;
     }
     //int赋值给对象 
     test & operator=(const int &t1){
         v = t1;
         return *this;
     }
    
   /*如下重载加号 + */
     //对象加上 int 
     test operator+(const int & a){
         test t1;
         t1.v = v + a;
         return t1;
     }
     //对象加对象 
     test operator+(test &t1){
         test t2;
         t2.v = v + t1.v;
         return t2;
     }
    
   /*如下重载加等号 += */  
     //对象加上对象 
     test &operator+=(const test &t1){
         v += t1.v;
         return *this;
     }  
     //对象加上int
     test &operator+=(const int &a){
         v += a;
         return *this;
     }

   /*如下重载双等号 == */  
     //对象==对象 
     bool operator==(const test &t1)const{
         return (v == t1.v);
     }  
     //对象==int
     bool operator==(const int &t1)const{
         return (v == t1);
     }  
    
   /*如下重载 输入>> 输出<< */
     /*友元函数,输出对象*/
     friend inline ostream & operator << (ostream & os, test &t1){
         cout << "class t(" << t1.v << ")" << endl;
         return os;
     }
     /*友元函数,输入对象*/
     friend inline istream & operator >> (istream & is, test &t1){
         cin >> t1.v;
         return is;
     }
};
相关文章
相关标签/搜索