C++ 实验7 运算符重载

定义一个复数类,重载运算符“+”、“-”、“*”、“、”,使之能用于复数的加、减、乘、除。要求:重载运算符“+”、“-”用成员函数;重载运算符“*”、“/”用友元函数,实现两个复数的和、差、积、商。

代码如下:


 头文件()代码如下:

#pragma once
class complex {
private:
	double real;//实部
	double image;//虚部
public:
	complex();//不带参构造函数
	complex(double r, double i);//带参构造函数。
	void show();//打印输出
	complex operator+(complex& a);//用成员函数,重载运算符“+”
	complex operator-(complex& a); //用成员函数,重载运算符“ - ”
	//用友元函数,重载运算符“ * ”
	friend complex operator*(complex& a,complex &b);
	//用友元函数,重载运算符“ / ”
	friend complex operator/(complex& a, complex& b);
	~complex();	
};

 main代码如下:

#include<iostream>
using namespace std;
#include"anew.h"

complex::complex() {
	real = 0;
	image = 0;
}
complex::complex(double r, double i) {
	real = r;
	image = i;
}
complex complex::operator+(complex& a) {
	complex temp;
	temp.real = real + a.real;
	temp.image = image + a.image;
	return temp;
}

complex complex::operator-(complex& a) {
	complex temp;
	temp.real = real - a.real;
	temp.image = image - a.image;
	return temp;
}

complex operator*(complex& a, complex& b) {
	complex temp;
	temp.real = a.real * b.real - a.image * b.image;
	temp.image = a.image * b.real + a.real * b.image;
	return temp;
}
complex operator/(complex& a, complex& b) {
	complex temp;
	temp.real = (a.real * b.real +a.image * b.image)/(b.real*b.real+b.image*b.image);
	temp.image=(a.image*b.real-a.real*b.image)/(b.real * b.real + b.image * b.image);
	return temp;
}

void complex::show() {
	cout << "(" << real << "," << image << "i"<<")" << endl;
}

void main()
{
	complex a1(1,2),a2(3,4);
	cout << "两个复数为:"<<endl;
	cout <<"a1=";
	a1.show();
	cout << "a2=";
	a2.show();

	complex sum,sub,mul,div;
	cout << "两个复数相加为:" << endl;
	sum = a1 + a2;
	cout << "a1+a2=";
	sum.show();
	cout << "两个复数相减为:" << endl;
	sub = a1 - a2;
	cout << "a1-a2=";
	sub.show();
	cout << "两个复数相乘为:" << endl;
	mul = a1 * a2;
	cout << "a1*a2=";
	mul.show();
	cout << "两个复数相除为:" << endl;
	div = a1 / a2;
	cout << "a1/a2=";
	div.show();
	
}

运行截图如下:

 


代码仅供参考

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值