问题及代码:
/*Copyright (c)2016,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:main.cpp
*作 者:崔青青
*完成日期:2016年5月18日
*版 本 号:v1.0
*问题描述:实现复数类中的运算符重载。
*输入描述:
*输出描述:
*/
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(){real=0;image=0;}
Complex(double r,double i)
{
real=r;
image=i;
}
friend Complex operator+(const Complex &c1,const double &d);
friend Complex operator-(const Complex &c1,const double &d);
friend Complex operator*(const Complex &c1,const double &d);
friend Complex operator/(const Complex &c1,const double &d);
void display();
private:
double real;
double image;
};
Complex operator+(const Complex &c1,const double &d)
{
Complex c;
c.real=c1.real+d;
c.image=c1.image;
return c;
}
Complex operator-(const Complex &c1,const double &d)
{
Complex c;
c.real=c1.real-d;
c.image=c1.image;
return c;
}
Complex operator*(const Complex &c1,const double &d)
{
Complex c;
c.real=c1.real*d;
c.image=c1.image;
return c;
}
Complex operator/(const Complex &c1,const double &d)
{
Complex c;
c.real=c1.real/d;
c.image=c1.image;
return c;
}
void Complex::display()
{
cout<<"("<<real<<" "<<image<<")"<<endl;
}
int main()
{
Complex c1(3,4),c2(5,-10),c3;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c3=c1+2;
cout<<"c1+2=";
c3.display();
c3=c1-2;
cout<<"c1-2=";
c3.display();
c3=c1*2;
cout<<"c1*2=";
c3.display();
c3=c1/2;
cout<<"c1/2=";
c3.display();
return 0;
}
运行结果:
知识点总结:
运算符重载函数,与实数相加的时候,要用两个参数。
学习心得:
运算符重载函数可以提高程序效率。