复数类的简单实现


Complex.h
#ifndef _COMPLEX_H_
#define _COMPLEX_H_
class Complex{
	friend std::istream& operator>>(std::istream& in,Complex&);
	friend std::ostream& operator<<(std::ostream& out,Complex&);
public:
	Complex();
	Complex(float);
	Complex(float,float);
	Complex(const Complex&);
	float getReal()const;
	float getImg()const;
	void setReal(float);
	void setImg(float);
	Complex operator+(const Complex&);
	Complex operator-(const Complex&);
	Complex operator*(const Complex&);
	Complex operator/(const Complex&);
	Complex& operator=(const Complex& op);
private:
	float real;
	float img;
};
#endif

Complex.cpp
#include<iostream>
#include "Complex.h"
using namespace std;
Complex::Complex()
{
	real=0;
	img=0;
}
Complex::Complex(float real)
{
	this->real=real;
	this->img=0;
}
Complex::Complex(float real,float img)
{
	this->real=real;
	this->img=img;
}

Complex::Complex(const Complex&op)
{
	real=op.real;
	img=op.img;
}


float Complex::getReal()const
{
	return real;
}
float Complex::getImg()const
{
	return img;
}
void Complex::setReal(float real)
{
	this->real=real;
}
void Complex::setImg(float img)
{
	this->img=img;
}
Complex Complex::operator+(const Complex& op)
{
	Complex result;
	result.real=real+op.real;
	result.img=img+op.img;
	return result;
}

Complex Complex::operator-(const Complex& op)
{
	Complex result;
	result.real=real-op.real;
	result.img=img-op.img;
	return result;
}

Complex Complex::operator*(const Complex& op)
{
	Complex result;
	result.real=real*op.real-img*op.img;
	result.img=real*op.img+img*op.real;
	return result;
}

Complex Complex::operator/(const Complex& op)
{
	if(op.real==0&&op.img==0)
	{
		cerr<<"除数为0!"<<endl;
		exit(-1);
	}
	Complex result;
	double deno=op.real*op.real+op.img*op.img;
	result.real=(real*op.real+img*op.img)/deno;
	result.img=(img*op.real-real*op.img)/deno;
	return result;
}
Complex& Complex::operator=(const Complex& op)
{
	real=op.real;
	img=op.img;
	return *this;
}
istream& operator>>(istream& in,Complex&op)
{
	return in>>op.real>>op.img;
}
ostream& operator<<(ostream& out,Complex&op)
{
	if(op.real==0&&op.img==0)return out<<0<<endl;
	if(op.real!=0)out<<op.real;
	if(op.img==0)return out<<endl;
	if(op.img>0)
	{
		if(op.real!=0)out<<"+";
		if(op.img==1)out<<"i";
		else out<<op.img<<"i";
	}
	else
	{
		if(op.img==-1)out<<"-i";
		else out<<op.img<<"i";

	}
	return out<<endl;
}
main.cpp
#include<iostream>
#include "Complex.h"
using namespace std;

int main()
{
	Complex comp1,comp2;
	cin>>comp1>>comp2;
	cout<<comp1+comp2<<comp1-comp2<<comp1*comp2;
	cout<<comp1/comp2;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值