/*复数类:CComplex;
C++ 的运算符重载:使对象的运算表现的和编译器内置类型一样。
*/
#include<iostream>
using namespace std;
class CComplex{
public:
//这里相当于定义了三个构造函数。
CComplex(int r=0,int i=0):mreal(r),mimage(i){}
CComplex operator+(const CComplex &src){//不能返回对象的指针。
return CComplex(this->mreal+src.mreal,this->mimage+src.mimage);
}
void show(){
cout<<this->mreal<<" "<<this->mimage<<endl;
}
/*
++运算符的重载
operator++()前置++。前置++返回的是引用
operator++(int) 后置++;后置++返回的是临时对象。
*/
CComplex & operator++(){
mreal+=1;
mimage+=1;
return *this;//前置++
}
CComplex operator++(int){
return CComplex(mreal++,mimage++);
}
private :
int mreal;
int mimage;
friend CComplex operator+(const CComplex &x,const CComplex &y);
friend ostream& operator<<(ostream&os,const CComplex &cmp);
};
CComplex operator+(const CComplex &x,const CComplex &y){
return CComplex(x.mreal+y.mreal,x.mimage+y.mimage);
}
ostream& operator<<(ostream&os,const CComplex &cmp){
cout<<"mreal:"<<cmp.mreal<<" mimage:"<<cmp.mimage<<endl;;
}
int main(){
CComplex cmp1(10,10);
CComplex cmp2(20,20);
CComplex cmp3=cmp1+cmp2;
cmp3.show();
CComplex cmp4=cmp1+20;
cmp4.show();
//编译器在做对象运算的时候,会调用对象的运算符重载函数
//优先调用成员方法;如果没有成员方法,
//就在全局作用域找合适的运算符重载函数。
CComplex cmp5=20+cmp1;
cmp5.show();
cout<<cmp5;
return 0;
}
C++运算符重载,复数类
最新推荐文章于 2022-02-24 14:41:58 发布