cpp课程总结--运算符重载

//运算符重载
/*可以对已有的预定义运算符重载、不能改变个数、不改变优先级、功能相似*/
/*"."".*""::""?:"不能被重载*/
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>> 
*/
/*[]看作双目运算符,只能重载为成员函数*/










 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值