//运算符重载
/*可以对已有的预定义运算符重载、不能改变个数、不改变优先级、功能相似*/
/*"."".*""::""?:"不能被重载*/
int operator+ (int b);
/*单目不设置参数 双目设置一个参数*/
int a,b;
a=a+b;
a=a.operator+(b);
class com{
private:
double a;
double i;
public:
com(double a=0.0,double i=0.0);
void show();
com operator+(com &c);
com operator=(com &c);
com operator++();
com operator++(int);
friend istream& operator>>(isrteam &is,com &c);//返回值是istream& //只能是友员
friend ostream& operator<<(ostream &is,com &c); //注意是引用
friend com operator-(com &c1,com &c2)//重载-运算符,重载为类的有元函数
};
istream & operator >> (isrteam &is,com &c){
is >> c.r >> c.i;
return is;
}
ostream& operator<<(ostream &is,com &c){
is << c.r << " " << c.i << endl;
}
com::com(double a,double i){
this->a=a;
this->i=i;
}
com com::operator++(int){
com t;
t = *this;
this->a=this->a+1;
this->i=this->i+1;
return t;
}
com com::operator++(){
this->a=this->a+1;
this->i=this->i+1;
return *this;
}
void com::show(){
cout << "<" << a << ","<< b << "i>";
}
com com::operator=(com &c){
this->a=c.a;
this->i=c.i;
return *this;//this是对应的地址
}
com com::operator+(com &c){
com t;
t.a=this->a+c.a;
t.i=this->i+c.i;
return t;
}
com operator-(com &c1,com &c2){
com t;
t.a = c1.a - c2.a;
t.i = c1.i - c2.i;
return t;
}
int main(){
com c1;
com c2(10,20) , c3(15,25);
c1 = c2+c3;
c1.show();
c1 = c2-c3;
c1.show();
c1=c2;
++cc2;
c1.show();
c2.show();
}
//重载为类的友元函数/*参数个数=操作数个数*/
//++a区别a++; a++带一个参数
//一般单目重载为成员函数 双目为有员
// 有些只能成员函数 有些只能友元函数
a=b;//赋值运算符 1.赋值 2.运算式子有值
a=b=c;//先进行b=c,然后a=b 从右向左
/*cout是ostream类的对象,cin是istream类的对象
>>对应的是operator>>
*/
/*[]看作双目运算符,只能重载为成员函数*/
cpp课程总结--运算符重载
于 2024-04-26 19:06:26 首次发布