c++运算符重载


complex.h

#ifndef _COMPLEX_H_
#define _COMPLEX_H_
#include <iostream>
using namespace std;
class Complex{
	friend ostream& operator<<(ostream& out,const Complex& c);
	friend istream& operator>>(istream& input,Complex& c);
	friend Complex operator*(const Complex c1,const Complex c2);
	friend Complex operator/(const Complex c1,const Complex c2);
	friend Complex& operator++(Complex&c);//前缀
	friend Complex operator++(Complex&c,int);//后缀
public:
	Complex(int x=1,int y=1):a(x),b(y){};
	Complex operator+(const Complex c);
	Complex operator-(const Complex c);
	Complex& operator--();//前缀
	Complex operator--(int);//后缀
	operator int();//只能是成员函数 不必写返回值类型 无形参 强制类型转换
protected:
private:
	int a;
	int b;
};
#endif
/*不能重载的运算符只有5个:类属关系运算符“.”,成员指针运算符“*”,作用域分辨符“::”,sizeof运算符和三目运算符“?:”*/
Complex.cpp


#include "Complex.h"

ostream& operator<<(ostream& out,const Complex& c){
	if (c.a==0){
		if (c.b==0)
			out<<"0";
		else
			out<<c.b<<"i";
	}else if (c.b<0){
		out<<c.a<<c.b<<"i";
	}else  if(c.b==0){
		out<<c.a;
	}else{
		out<<c.a<<"+"<<c.b<<"i";
	}
	return out;
}

istream& operator>>(istream& input,Complex& c){
	cout<<"please input the a and b:";
	input>>c.a>>c.b;
	return input;
}

Complex Complex::operator +(const Complex c){
	return Complex(a+c.a,b+c.b);
}

Complex Complex::operator -(const Complex c){
	return Complex(a-c.a,b-c.b);
}

Complex operator*(const Complex c1,const Complex c2){
	int aa = c1.a*c2.a-c1.b*c2.b;
	int bb = c1.a*c2.b+c1.b*c2.a;
	return Complex(aa,bb);
}

Complex operator/(const Complex c1,const Complex c2){
	int aa = (c1.a*c2.a+c1.b*c2.b)/(c2.a*c2.a+c2.b*c2.b);
	int bb = (c1.b*c2.a+c1.a*c2.b)/(c2.a*c2.a+c2.b*c2.b);
	return Complex(aa,bb);
}

Complex& operator++(Complex&c){//前缀
	c.a +=10;
	return c;
}

Complex& Complex::operator --(){//前缀
	a -= 10;
	return *this;
}

Complex operator++(Complex&c,int){//后缀
	Complex old(c);
	c.a +=1;
	return old;
}

Complex Complex::operator --(int){//后缀
	Complex old(*this);
	a -= 1;
	return old;
}

Complex::operator int(){
	return a;
}
main.cpp

#include "complex.h"
#include <iostream>

using namespace std;

int main(){
	cout<<"hello world!"<<endl;
	Complex c(1,2);
	cout<<"c="<<c<<endl;
	Complex cc;
	cin>>cc;
	cout<<"cc="<<cc<<endl;
	cout<<"cc+c="<<cc+c<<endl;
	cout<<"cc-c="<<cc-c<<endl;
	cout<<"cc*c="<<cc*c<<endl;
	cout<<"cc/c="<<cc/c<<endl;
	cout<<"++cc="<<++cc<<endl;
	cout<<"--c="<<--c<<endl;
	cout<<"cc++="<<cc++<<endl;
	cout<<"cc="<<cc<<endl;
	cout<<"c--="<<c--<<endl;
	cout<<"c="<<c<<endl;
	cout<<"int(c)="<<int(c)<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值