C++ 复数类四则运算重载以及输入输出重载

#include <iostream>
#include <cstdlib>
#include <limits>
#include <iomanip>
#include <cmath>

using namespace std;

class MyComplex//2. 创建一个类 MyComplex,用来表示复数。
{
public:
	MyComplex()
	{}
	MyComplex(double a, double b):real(a),imag(b)
	{}
	friend ostream& operator <<(ostream& os, const MyComplex& z);
	friend istream& operator >> (istream& is, MyComplex& z);
	MyComplex operator+(const MyComplex &z);
	MyComplex operator-(const MyComplex &z);
	MyComplex operator*(const MyComplex &z);
	MyComplex operator/(const MyComplex &z);

private:
	double real;
	double imag;
};


ostream & operator<<(ostream & os, const MyComplex & z)
{
	
	os.unsetf(std::ios::showpos);
	os << "(" << z.real;
	os.setf(std::ios::showpos);
	os << z.imag << "i)";
	return os;
}

istream & operator >> (istream & is, MyComplex & z)
{
	// TODO: 在此处插入 return 语句
	is >> z.real >> z.imag;
	return is;
}

MyComplex MyComplex::operator+(const MyComplex & z)
{
	return MyComplex(real + z.real, imag + z.imag);
}

MyComplex MyComplex::operator-(const MyComplex & z)
{
	return MyComplex(real - z.real, imag - z.imag);
}

MyComplex MyComplex::operator*(const MyComplex & z)
{
	return MyComplex(real * z.real - imag * z.imag, z.real * imag + z.imag * real);
}

MyComplex MyComplex::operator/(const MyComplex & z)
{
	if (pow(z.real, 2) + pow(z.imag, 2) == 0)
	{
		cout << "Divisor can not be 0";
		exit(0);
	}

	return MyComplex((real * z.real + imag * z.imag) / (pow(z.real, 2) + pow(z.imag, 2)), (imag * z.real - real * z.imag) / (pow(z.real, 2) + pow(z.imag, 2)));
}

int main() {
	MyComplex z1, z2;
	cin >> z1;
	cin >> z2;
	cout << "z1 + z2 = " << z1 + z2 << endl;
	cout << "z1 - z2 + z1 = " << z1 - z2 + z1 << endl;
	cout << "z1 * z2 - z1 = " << z1 * z2 - z1 << endl;
	cout << "z1 / z2 + z1 = " << z1 / z2 + z1 << endl;
	cout << "z2 - z1 / z1 = " << z2 - z1 / z1;
	// GCC及VC编译器在调试模式下会暂停,便于查看运行结果
#if ( defined(__DEBUG__) || defined(_DEBUG) )
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	cin.get();
#endif
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值