C++复数类重载简单运算

定义一个表示复数的Complex类,包含实部和虚部的两个属性。

在类的外部以友元函数的形式重载+、-、*等运算符。

class Complex{
public:
	Complex(double r,double i){
		……
	}
	//友元函数声明
private:
	double real,image; 

要求在函数中给出测试程序,运算结果要符合数学意义。

接下来,为其重载输入输出流。以使用cin和cout关键字对Complex的对象进行输入输出。

#include <iostream>
using namespace std;

class Complex{
public:
	Complex(double r=0,double i=0){
		real = r;
		image = i;
	}
	
	friend Complex operator +(Complex x,Complex y);  //重载加法运算 
	friend Complex operator -(Complex x,Complex y);  //重载减法运算 
	friend Complex operator *(Complex x,Complex y);  //重载乘法运算 
	friend ostream& operator <<(ostream&,const Complex&);  //重载输出流 
	friend istream& operator >>(istream&,Complex&);  //重载输入流 
private:
	double real,image;
}; 

Complex operator +(Complex x,Complex y){
	return Complex(x.real+y.real,x.image+y.image);
}
Complex operator -(Complex x,Complex y){
	return Complex(x.real-y.real,x.image-y.image);
}
Complex operator *(Complex x,Complex y){
	return Complex(x.real*y.real-x.image*y.image,x.real*y.image+x.image*y.real);
}

ostream& operator << (ostream& os,const Complex& c){
	if(c.real != 0)
		os << c.real;
	if(c.image > 0)
		os << '+' << c.image << 'i';
	if(c.image < 0)
		os << c.image << 'i';
	return os;
} 

istream& operator >>(istream& is,Complex& c){
	cout << "输入实部:";
	is >> c.real;
	cout << "输入虚部:";
	is >>c.image;
	return is; 
}

int main(){
	Complex c1,c2;
	cout << "输入c1:"<< endl;
	cin >> c1;
	cout << "c1 = " << c1 << endl; 
	cout << "输入c2:" << endl;
	cin >> c2;
	cout << "c2 = " << c2 << endl;
	Complex c3 = c1 + c2;
	Complex c4 = c1 - c2;
	Complex c5 = c1 * c2;
	cout << "c1 + c2 = " << c3 << endl;
	cout << "c1 - c2 = " << c4 << endl;
	cout << "c1 * c2 = " << c5 << endl;
	return 0;
}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值