<一>关于运算符重载

C++的运算符重载:使对象的运算表现得和编译器内置类型一样
如下代码,如果T是整形,那很好理解,但是如果 T 是一个 Student 类, a + b ?怎么操作,两个学生类怎么相加?
这个就是我们要说的运算符重载问题

template<typename T>
T sum(T a,T b){
   return a + b;  // a.+(b)  => a.operator+(b)  operator+ 就是我们需要的函数
}
CComplex operator+(const CComplex &lhs, const CComplex &rhs){

   reutrn CComlex(lhs.x+rhs.x,lhs.y+rhs.y);
   // 由于不能再类外访问CComplex的私有成员,所以我们可以加上友元
   // 在CComplex 加上 firend CComplex operator+(const CComplex &lhs, const CComplex &rhs);

}

ostream & operator<<(ostream & cout, const CComplex & val){
    cout<<"Complex = "<<val.x <<" "<<val.y<<endl;
    return out
}



class CComplex{

public:
  CComplex(int _x=1,int _y=1):x(_x),y(_y){}

  Complex operator+(const CComplex & _com){
       CComplex _comp;
       _comp.x= this->x + _com.x
       _comp.y= this->y +_com.y;
       return _comp;
  }

  //后置++,返回的是 + 之前的值
  Complex operator++(int){
     CComplex tep=*this;
     x++;
     y++;
     return tep;
  }

  //前置++ 返回加后的值
  Complex & operator++(){
     x++;
     y++;
     return *this;
  }

  //+=不需要返回值
  void operator+=(const CComplex & _value){
      x=x+_value.x;
      y=y+_value.y;
  }


private:
    int x;
    int y;
    firend CComplex operator+(const CComplex &lhs, const CComplex &rhs);
    firend ostream & operator<<(ostream & cout, const CComplex & val) ;
}

int main(){
    
    CComplex comp1(100,200);
    CComplex comp2(1,2);
    CComplex  comp3=comp1 + comp2;


    CComplex  comp4=comp1 + 20;//comp1.operator+(CComplex tep) => comp1.operator+(将20转为CComplex对象) 
   //这个时候编译器会想办法 把 20转为CComplex对象,在上面的类中,可以转,因为 CComplex(int _x=1,int _y=1) 有默认值
   //所以上面代码 会使用20创建一个CComplex 对象,然后 再让他们相加

   CComplex  comp5=30 +comp1;//编译报错 30.operator+(CComplex tep)  整形数的加法运算符里面没有operator+(CComplex tep) 编译器不会把30转为CComplex对象
   
   //编译器在做对象的运算的时候,会调用对象的运算符重载函数(优先调用成员方法),r如果没有成员方法
   //就会在全局作用域中找合适的运算符重载函数 所以 CComplex  comp5=30 +comp1 编译器
   //当在整数中找不到成员方法是,还可以 ::operator+(30,comp1) 在全局作用域中找运算符重载函数
   //就会调用全局作用域中的 CComplex operator+(const CComplex &lhs, const CComplex &rhs) 方法,
   //所以如果希望CComplex  comp5=30 +comp1;编译通过,可以加上全局函数 CComplex operator+(const CComplex &lhs, const CComplex &rhs)


   return 0;
}


原文链接: https://www.cnblogs.com/erichome/p/16909682.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    <一>关于运算符重载

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/5116

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月4日 下午7:20
下一篇 2023年2月4日 下午7:20

相关推荐