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;
}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭