/*
*Corpyright (c)2013,烟台大学计算机学院
*All right reseved.
*作者:z张梦佳
*完成日期:2014年4月14日
*版本号:v1.0
*输入描述:
*问题描述:复shu类!
*程序输出:
*问题分析:
*算法设计:
*/
#include <iostream>
#include <cmath>
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r; imag=i;}
Complex operator+(double a);
Complex operator-(double a);
friend Complex operator+(double x,Complex c);
friend Complex operator-(double x,Complex c);
void display();
double geta()
{
return real;
}
double getb()
{
return imag;
}
private:
double real;
double imag;
};
//下面定义成员函数
Complex Complex::operator+(double a)
{
return Complex(a+real,imag);
}
Complex Complex::operator-(double a)
{
return Complex(a-real,imag);
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<")"<<endl;
}
int main()
{
Complex c1(3,4),c2;
double d=10;
cout<<"c1+d"<<endl;
c2=c1+d;
c2.display();
cout<<"c1-d"<<endl;
c2=c1-d;
c2.display();
cout<<"d+c1"<<endl;
c2=d+c1;
c2.display();
cout<<"d-c1"<<endl;
c2=d-c1;
c2.display();
return 0;
}
Complex operator+(double x,Complex c)
{
return Complex(x+c.real,c.imag);
}
Complex operator-(double x,Complex c)
{
return Complex(x-c.real,c.imag);
}
感悟
这个题告诉我,平时认为理所当然的事也有很多漏洞。