sy4_多态的应用_2.1_运算符重载为成员函数
(2)设计程序实现复数的加法和乘法运算,要求使用两种方法实现:第一种方法:将加法运算符和乘法运算符重载为成员函数,使之能够实现复数的加法和乘法运算。
实现思路:
成员函数运算符的格式如下:
函数类型 operator 运算符名称(形参列表)
{
对运算符的重载处理
}
调用成员函数运算符的格式如下:
对象名.operator 运算符(参数)
它等价于
<对象名> 运算符 <参数>
例如:
a.operator+(b)等价于a+b
根据题意设计加法运算符和乘法运算符重载为成员函数,使之能够实现复数的加法和乘法运算。
Complex operator+(Complex c)
{
Complex x;
x.real = real + c.real;
x.imag = imag + c.imag;
return x;
}
Complex operator*(Complex c)
{
Complex y;
y.real = real * c.real - imag * c.imag;
y.imag = real * c.imag + imag * c.real;
return y;
}
在输出设计中,由于复数的形式分类,可分为实数,虚数,以及纯虚数,且嵌套逻辑比较简单,设计如下
if (imag != 0)//虚数a±bi
{
if (real != 0)//虚数a±bi
{
if (imag > 0)//虚数a+bi
{
cout << "虚数=" << real << "+" << imag << "i" << endl;
}
else//虚数a-bi
{
cout << "虚数=" << real << imag << "i" << endl;
}
}
else//纯虚数bi
{
cout << "纯虚数=" << imag << "i" << endl;
}
}
else//实数a
{
cout << "实数=" << real << endl;
}
整段代码:
#include <iostream>
#include "math.h";
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
Complex();
Complex(double r, double i);
void display();
Complex operator+(Complex c);
Complex operator*(Complex c);
};
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
void Complex::display()
{
if (imag != 0)//虚数a±bi
{
if (real != 0)//虚数a±bi
{
if (imag > 0)//虚数a+bi
{
cout << "虚数=" << real << "+" << imag << "i" << endl;
}
else//虚数a-bi
{
cout << "虚数=" << real << imag << "i" << endl;
}
}
else//纯虚数bi
{
cout << "纯虚数=" << imag << "i" << endl;
}
}
else//实数a
{
cout << "实数=" << real << endl;
}
}
Complex Complex::operator+(Complex c)
{
Complex x;
x.real = real + c.real;
x.imag = imag + c.imag;
return x;
}
Complex Complex::operator*(Complex c)
{
Complex y;
y.real = real * c.real - imag * c.imag;
y.imag = real * c.imag + imag * c.real;
return y;
}
int main()
{
Complex c1(5, 0), c2(0, 5), c3(5, 4), c4(3, -2);
Complex S, P;
cout << "c1为";
c1.display();
cout << "c2为";
c2.display();
cout << "c3为";
c3.display();
cout << "c4为";
c4.display();
cout << "c3+c4为";
S = c3.operator+(c4); //S = c3 + c4;
S.display();
cout << "c3*c4为";
P = c3.operator*(c4); //P = c3 + c4;
P.display();
return 0;
}