C++的运算符重载:使对象的运算表现得和编译器内置类型一样
如下代码,如果T是整形,那很好理解,但是如果 T 是一个 Student 类, a + b ?怎么操作,两个学生类怎么相加?
这个就是我们要说的运算符重载问题
template
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;
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。