/*
* Copyright (c) 2013, 烟台大学计算机学院
* All rights reserved.
* 作 者: 沈远宏
* 完成日期:2013 年 04月22日
* 版 本 号:v1.0
* 问题描述:请用类的友元函数,而不是成员函数,定义复数类重载运算符+、-、*、/,使之能用于复数的加减乘除
再定义一目运算符 -,-c相当于0-c。
(2)定义Complex类中的<<和>>运算符的重载,实现输入和输出,改造原程序中对运算结果显示方式,使程序读起来更自然。
* 输出:两个复数+,-,*,/后的结果输出
* 输出:两个复数+,-,*,/后的结果输出
*/
#include <iostream>
using namespace std;
class Complex
{
public:
Complex()
{
real=0;
imag=0;
}
Complex(double r,double i)
{
real=r;
imag=i;
}
friend Complex operator+(Complex &c1,Complex &c2);
friend Complex operator-(Complex &c1,Complex &c2);
friend Complex operator-(Complex &c1);
friend Complex operator*(Complex &c1,Complex &c2);
friend Complex operator/(Complex &c1,Complex &c2);
void display();
void input();
private:
double real;
char p,i;
double imag;
};
//下面定义成员函数
Complex operator+(Complex &c1,Complex &c2)
{
return Complex(c1.real+c2.real,c1.imag+c2.imag);
}
Complex operator-(Complex &c1,Complex &c2)
{
return Complex(c1.real-c2.real,c1.imag-c2.imag);
}
Complex operator-(Complex &c1)
{
return Complex(-c1.real,-c1.imag);
}
Complex operator*(Complex &c1,Complex &c2)
{
return Complex((c1.real*c2.real-c2.imag*c1.imag),(c1.real*c2.imag+c1.imag*c2.real));
}
Complex operator/(Complex &c1,Complex &c2)
{
return Complex((c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag),(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag));
}
void Complex::display()
{
if(imag>0)
{
p='+';
}
else
{
p='-';
imag=-imag;
}
cout<<real<<p<<imag<<"i\n";
}
void Complex::input()
{
cin>>real>>p>>imag>>i;
}
//下面定义用于测试的main()函数
int main()
{
Complex c1,c2,c3;
cout<<"请输入两个复数:";
c1.input();
c2.input();
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=c1-c2;
cout<<"c1-c2=";
c3.display();
c3=c1*c2;
cout<<"c1*c2=";
c3.display();
c3=c1/c2;
cout<<"c1/c2=";
c3.display();
c3=-c1;
cout<<"-c1=";
c3.display();
c3=-c2;
cout<<"-c2=";
c3.display();
return 0;
}
运行结果:
心得体会:、
老师你什么时候来个放假类啊,会不会很有激情