4-1 复数类的运算符重载
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
通过本题目的练习可以掌握成员运算符重载及友元运算符重载
要求定义一个复数类,重载加法和减法运算符以适应对复数运算的要求,重载插入运算符(<<)以方便输出一个复数的要求。
Input
要求在主函数中创建对象时初始化对象的值。
Output
输出数据共有4行,分别代表a,b的值和它们求和、求差后的值
Example Input
无
Example Output
a=3.2+4.5i b=8.9+5.6i a+b=12.1+10.1i a-b=-5.7-1.1i
Hint
Author
#include <iostream>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
Complex(double re = 0, double im = 0) //构造函数初始化
{
real = re;
imag = im;
}
Complex operator + (Complex & c2) //对+重载
{
Complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
Complex operator - (Complex & c2) //对-重载
{
Complex c;
c.real = real - c2.real;
c.imag = imag - c2.imag;
return c;
}
void showComplex() //类私有不能直接输出,可以这样分类分块输出,也可以设置友元函数
{
if(imag > 0) //虚部为正,输出加号
cout << real << "+" << imag << "i" << endl;
else
cout << real << imag << "i" << endl;
}
};
int main()
{
Complex a(3.2, 4.5);
Complex b(8.9, 5.6);
cout << "a=";
a.showComplex();
cout << "b=";
b.showComplex();
Complex c1 = a + b;
Complex c2 = a - b;
cout << "a+b=";
c1.showComplex();
cout << "a-b=";
c2.showComplex();
return 0;
}