定义一个表示复数的Complex类,包含实部和虚部的两个属性。
在类的外部以友元函数的形式重载+、-、*等运算符。
class Complex{
public:
Complex(double r,double i){
……
}
//友元函数声明
private:
double real,image;
要求在函数中给出测试程序,运算结果要符合数学意义。
接下来,为其重载输入输出流。以使用cin和cout关键字对Complex的对象进行输入输出。
#include <iostream>
using namespace std;
class Complex{
public:
Complex(double r=0,double i=0){
real = r;
image = i;
}
friend Complex operator +(Complex x,Complex y); //重载加法运算
friend Complex operator -(Complex x,Complex y); //重载减法运算
friend Complex operator *(Complex x,Complex y); //重载乘法运算
friend ostream& operator <<(ostream&,const Complex&); //重载输出流
friend istream& operator >>(istream&,Complex&); //重载输入流
private:
double real,image;
};
Complex operator +(Complex x,Complex y){
return Complex(x.real+y.real,x.image+y.image);
}
Complex operator -(Complex x,Complex y){
return Complex(x.real-y.real,x.image-y.image);
}
Complex operator *(Complex x,Complex y){
return Complex(x.real*y.real-x.image*y.image,x.real*y.image+x.image*y.real);
}
ostream& operator << (ostream& os,const Complex& c){
if(c.real != 0)
os << c.real;
if(c.image > 0)
os << '+' << c.image << 'i';
if(c.image < 0)
os << c.image << 'i';
return os;
}
istream& operator >>(istream& is,Complex& c){
cout << "输入实部:";
is >> c.real;
cout << "输入虚部:";
is >>c.image;
return is;
}
int main(){
Complex c1,c2;
cout << "输入c1:"<< endl;
cin >> c1;
cout << "c1 = " << c1 << endl;
cout << "输入c2:" << endl;
cin >> c2;
cout << "c2 = " << c2 << endl;
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
Complex c5 = c1 * c2;
cout << "c1 + c2 = " << c3 << endl;
cout << "c1 - c2 = " << c4 << endl;
cout << "c1 * c2 = " << c5 << endl;
return 0;
}