上机——实验四

实验四:运算符重载

实验内容:
(1) 定义一个复数类 Complex,虚部和实部为私有数据类型。
(2) 重载加法运算符,减法运算符,+= 运算符。
(3) 重载一元负号和一元正号。
(4) 编写一个完整的程序,测试重载运算符的正确性。要求乘法“*”用友元函数实
现重载,除法“/”用成员函数实现重载。
在这里插入图片描述

代码如下:

#include <iostream>
using namespace std;
class complex{
	private:
  		double real, image;
	public:
		complex(double r = 0, double i = 0){ //声明构造函数进行初始化 
    		real = r; 
			image = i; 
	} 
	//成员函数重载运算符 +
		const complex operator+(const complex& right) const{
    		return complex (real+right.real,image+right.image);  
	}
	//成员函数重载运算符 - 
		const complex operator-(const complex& right) const{
    		return complex (real-right.real,image-right.image);  
	}
	//重载运算符 += 
		complex& operator+=(const complex& right){
			real+=right.real; 
			image+=right.image;
			return *this;
	}
	//重载一元运算符 -、+ 
		complex operator-(){
			return complex(-real,-image);
		}	
		complex operator+(){
			return complex(+real,+image);
		}
	//全局函数重载运算符 *	
		friend complex operator*(complex &c1,complex &c2);
	//成员函数重载运算符 / 
		complex operator/(complex &c){
    		double r,i;
    		r=(real*c.real+image*c.image)/(c.real*c.real+c.image*c.image);
    		i=(image*c.real-real*c.image)/(c.real*c.real+c.image*c.image);
    		return complex(r,i);
		} 
	//全局函数重载输入输出运算符
		friend ostream&  operator<<(ostream& os, const complex& c);
		friend istream&  operator>>(istream& is,complex& c);

};
//输入输出运算符函数的定义
ostream& operator<<(ostream& os, const complex& c){
   		if(c.real==0 && c.image==0){ 
		   os << "0"; 
	}
   		if(c.real!=0){ 
		   os << c.real;
	}
   		if(c.image!=0){
			if(c.image>0 && c.real!=0)
				os << "+";
				os << c.image << "i" <<endl;				
	}
   		return os; //返回ostream对象便于链式表达式
}

istream& operator>>(istream& is, complex& c){
		cout<<"请输入real, image:";
		return is>>c.real>>c.image;
}
//重载*运算符 (a+bi) * (c+di) = (ac-bd) + (bc+ad)i
complex operator*(complex &c1,complex &c2)
{
    	complex c;
    	c.real=c1.real*c2.real-c1.image*c2.image;
    	c.image=c1.image*c2.real+c1.real*c2.image;
    	return complex(c.real,c.image);
}
int main() {
		complex c1,c2;
		cin>>c1;   //调用全局函数operator>>
		cin>>c2;
	cout<<"c1+c2:";
		cout<<c1+c2<<endl; //调用全局函数operator<<
	cout<<"c1-c2:"; 		
		cout<<c1-c2<<endl;	//调用operator- 
	cout<<"c1*c2:";
		cout<<c1*c2<<endl;	//调用operator*	
	cout<<"c1/c2:";
		cout<<c1/c2<<endl;	//调用operator/
		
		c1+=c2;
	cout<<"c1+=c2:";		//调用operator+= 
		cout<<c1<<endl;
	cout<<"-c1:";			//调用一元调用operator- 
		cout<<(-c1)<<endl;
	cout<<"+c1:";			//调用一元调用operator+ 
		cout<<(+c1)<<endl;
}

说明:实验内容不只是这些,这里只给出示例代码作为参考~~

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白吧啦吧啦

小白白,您的打赏是我的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值