【题解】【多态】Complex

题目描述

定义一个复数类Complex,实现+、-、*、/、++(前置)、++(后置)的运算符重载

输入格式

输入共一行,四个浮点数,分别表示虚数q的实数部分和虚数部分和虚数w的实数部分和虚数部分

输出格式

输出共6行,分别输出q+w,q-w,q*w,q / w , q++ , ++w的值

输入输出样例

输入 #1 复制

4 3 2 1

输出 #1 复制

6.00+4.00i
2.00+2.00i
5.00+10.00i
2.20+0.40i
4.00+3.00i
3.00+1.00i
#include<iostream>
#include<iomanip>
using namespace std;
class Complex{
	public:
		Complex(){real = 0;image = 0;}
		Complex(double r,double i){real = r;image = i;}
		Complex operator+(Complex &c2);
		Complex operator-(Complex &c2);
		Complex operator*(Complex &c2);
		Complex operator/(Complex &c2);
		Complex operator++();
		Complex operator++(int);
		void display();
	private:
		double real;
		double image;
}; 
int main(){
	double q_real,q_image,w_real,w_image;
	cin>>q_real>>q_image>>w_real>>w_image;
	Complex c1(q_real,q_image),c2(w_real,w_image),c3;
	c3 = c1 + c2;
	c3.display();
	c3 = c1 - c2;
	c3.display();
	c3 = c1 * c2;
	c3.display();
	c3 = c1 / c2;
	c3.display();
	c3 = c1++;
	c3.display();
	c3 = ++c2;
	c3.display();
	
return 0;	
} 
void Complex::display(){
	cout<<fixed<<setprecision(2);
	if(image > 0)
		cout<<real <<"+"<<image<<"i"<<"\n";
	else if(image < 0)
		cout<<real<<image<<"i"<<"\n";
	else 
		cout<<real;
}
Complex Complex::operator+(Complex &c2){
	Complex temp;
	temp.real = real + c2.real;
	temp.image = image + c2.image;
	return temp;
}
Complex Complex::operator-(Complex &c2){
	Complex temp;
	temp.real = real - c2.real;
	temp.image = image - c2.image;
	return temp;
}
Complex Complex::operator*(Complex &c2){
	Complex temp;
	temp.real = real * c2.real - image*c2.image;
	temp.image = image*c2.real + real*c2.image;
	return temp;
}
Complex Complex::operator/(Complex &c2){
	Complex temp;
	temp.real = (real * c2.real + image*c2.image) / (c2.real*c2.real + c2.image*c2.image);
	temp.image = (image*c2.real - real*c2.image) /	(c2.real*c2.real + c2.image*c2.image);
	return temp;
}
Complex Complex::operator++(){
	real++;
	return *this;
}
Complex Complex::operator++(int){

	Complex temp(*this);
	++(*this);
	return temp;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值