【sy4_多态的应用_2.1_运算符重载为成员函数】

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;
}
运行结果:

image-20220927224750429

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值