一、对复数进行运算符重载
1、加法运算符重载
1、因为我们要输入复数的值,所以我们应当运用构造函数,我们不仅要定义默认构造函数,来构造m3,还要定义一个构造函数使输入的数相加。
2、对于不涉及到数据类型转换的问题,我们使用运算符重载时一般将运算符重载函数的形参设置为对象的引用,可以减少时间和空间的开销,同时可以借助虚实结合通过引用改变实参的值。但是,当在使用运算符重载的同时,要使用转换构造函数(如Complex(double r){real=r;imag=0;})和类型转换函数(operator 类型名(){}),运算符重载函数的形参就不能使用引用,否则无法完成数据转换,编译不通过。
下面展示一些 代码
。
#include <iostream>
using namespace std;
class complex
{
friend complex operator+(complex m1,complex m2);
friend ostream & operator<<(ostream &cout,complex p);
friend void test01();
friend void test02();
public:
complex(){
};//构造一个默认构造函数
complex(int real1,int image1)
{
real=real1;
image=image1;
}
private:
int real;
int image;
};
//重载+号运算符
complex operator+(complex m1,complex m2)
{
//return complex(m1.real+m2.real,m2.image+m2.image);
complex temp;//两种方法都可以,不过用这一种方法就必须有默认构造函数
temp.real=m1.real+m2.real;
temp.image=m1.image+m2.image;
return temp;
}
//重载左移运算符<<
ostream & operator<<(ostream &cout,complex p)
{
cout<<"实部:"<<p.real<<endl;
cout<<"虚部:"<<p.image<<endl;
return cout;
}
void test01()//重载加号运算符
{
int a,b,c,d;
cout<<"请输入复数m1:(只输入实部和虚部)"<<endl;
cin>>a>>b;
complex m1(a,b);//这个就相当于 complex m1=complex(a,b);
cout<<"请输入复数m2:(只输入实部和虚部)"<<endl;
cin>>c>>d;
complex m2(c,d);
complex m3=m1+m2;
cout<<"复数m3为:"<<endl;
cout<<m3.real<<"+"<<m3.image<<"i"<<endl;
}
void test02()//重载<<运算符
{
int a,b;
cout<<"请输入复数m1:(只输入实部和虚部)"<<endl;
cin>>a>>b;
complex m1(a,b);
cout<<m1<<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
运行结果: