利用操作符重载实现虚数类

啥也不说了直接上代码 微笑小哥我的态度很好吧
//2、利用操作符重载给出一个完整的复数类的定义。
#include <iostream>
using namespace std;
class Complex{
	double real;
	double imag;
public:
	Complex(){real = 0;imag = 0;}
	Complex (double r,double i){real = r;imag = i;}
	Complex operator +(Complex &c);
	Complex operator -(Complex &c);
	Complex operator *(Complex &c);
	Complex operator /(Complex &c);
	void show();

};
Complex Complex::operator+(Complex &c){
	double r = real+c.real;
	double i = imag+c.imag;
	return Complex(r,i);
}
Complex Complex::operator-(Complex&c){
	double r = real-c.real;
	double i = imag-c.imag;
	return Complex(r,i);
}
Complex Complex::operator*(Complex &c){
	double r = real*c.real-imag*c.imag;
	double i = imag*c.real+real*c.imag;
	return Complex(r,i);
}
Complex Complex::operator/(Complex &c){
	if (c.imag==0&&c.real==0)
	{
		cout<<"请输入正确的除数"<<endl;
		return Complex(0,0);
	}else{
		double r = (real*c.real+imag*c.imag)/(c.real*c.real+c.imag*c.imag);
		double i = (imag*c.real-real*c.imag)/(c.real*c.real+c.imag*c.imag);
		return Complex(r,i);
	}
}
void Complex::show(){
	cout<<real<<"+"<<imag<<"i"<<endl;;
}
void main(){
	Complex a(1,2),b(3,4),c;
	c = a/b;
	c.show();
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值