C++复数类,运算符重载,通过分式类实现

简要介绍

这期的内容不多,主要是在往期代码(分式类)的基础上实现了复数类的简易运算。分式类实现可以看我的往期文章,链接:C++实现分式类-和八哥的环球探险

往期代码的添加:

OptiCalculate.h中:

//取负重载
Fractional operator-();

OptiCalculate.cpp中:

Fractional Fractional::operator-(){
	this->molecule = -molecule;
	return *this;
}

头文件Complex.h

#pragma once
#include "OptiCalculate.h"	//见往期文章
class Complex
{
public:
	Complex();
	Complex(Fractional re,Fractional im);
	~Complex();

	//输出显示和重载
	void show()const;
	friend ostream& operator<<(ostream& out, Complex C);

	//相加重载
	void operator+=(Complex C);
	Complex operator+(Complex C);

	//相减重载
	void operator-=(Complex C);
	Complex operator-(Complex C);

	//相乘重载
	void operator*=(Complex C);
	Complex operator*(Complex C);

	//相除重载
	void operator/=(Complex C);
	Complex operator/(Complex C);
private:
	Fractional Re;
	Fractional Im;
};

Complex.cpp

//初始化参数列表进行构造和析构函数
#include "Complex.h"

Complex::Complex():Im(),Re(){}

Complex::Complex(Fractional re, Fractional im):Re(re),Im(im){}

Complex::~Complex(){}
//输出显示与重载
void Complex::show() const { cout << "(" << Re << "+" << Im << "j)"; } 
ostream& operator<<(ostream& out, Complex C) { C.show(); return out; }
//加法
void Complex::operator+=(Complex C){
	this->Re += C.Re;
	this->Im += C.Im;
	this->Re.simplify();
	this->Im.simplify();
}

Complex Complex::operator+(Complex C){
	Complex tmp = *this;
	tmp += C;
	return tmp;
}
//减法
void Complex::operator-=(Complex C){
	this->Re -= C.Re;
	this->Im -= C.Im;
	this->Re.simplify();
	this->Im.simplify();
}

Complex Complex::operator-(Complex C){
	Complex tmp = *this;
	tmp -= C;
	return tmp;
}
//乘法
void Complex::operator*=(Complex C){
	Fractional re = this->Re * C.Re - this->Im * C.Im;
	Fractional im = this->Re * C.Im + this->Im * C.Re;
	re.simplify();
	im.simplify();
	this->Re = re;
	re.~Fractional();
	this->Im = im;
	im.~Fractional();
}

Complex Complex::operator*(Complex C){
	Complex tmp = *this;
	tmp *= C;
	return tmp;
}
//除法
void Complex::operator/=(Complex C){
	C.Im = -C.Im;
	Complex up = *this * C;
	Fractional down = C.Im * C.Im + C.Re * C.Re;
	up.Im /= down;
	up.Re /= down;
	up.Im.simplify();
	up.Re.simplify();
	Re = up.Re;
	Im = up.Im;
	up.~Complex();
	down.~Fractional();
}

Complex Complex::operator/(Complex C){
	Complex tmp = *this;
	tmp /= C;
	return tmp;
}

测试代码main.cpp

#include"Complex.h"
int main() {
	Fractional f1(2, 5);
	Fractional f2 = 0.625;
	
	Complex c1(f1, f2);
	Complex c2(5, 8);
	cout << "c1 = " << c1 << endl;
	cout << "c2 = " << c2 << endl;
	Complex c3 = c1 + c2;
	cout << "c1 + c2 = " << c3 << endl;
	c3 = c1 - c2;
	cout << "c1 - c2 = " << c3 << endl;
	Complex c4 = c1 * c2;
	cout << "c1 * c2 ="<< c4 << endl;
	c3 = c4 / c1;
	cout << "c2 = " << c2 << endl;
	return 0;
}

测试结果如下:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值