C++学习笔记——运算符重载

运算符重载定义形式:
<函数类型> <类名> :: operator <操作符> (<参数表>)
{
函数体
{
备注:不能重载的运算符包括"::",".",".*","?:"

#include<iostream>
using namespace std;

class Complex{
	public:
		double real, imag;
	public:
		Complex(double r=0, double i=0){real=r;imag=i;}
		double Real(){return real;}
		double Imag(){return imag;}
		Complex operator +(Complex&);
		Complex operator +(double);
		bool operator ==(Complex);
		~Complex(){}
};

Complex Complex::operator +(Complex &c){
	Complex temp;
	temp.real=real+c.real;
	temp.imag=imag+c.imag;
	return temp;
}

Complex Complex::operator +(double d){
	Complex temp;
	temp.real=real+d;
	temp.imag=imag;
	return temp;
}

bool Complex::operator ==(Complex c){
	if(real==c.real && imag==c.imag) return true;
	else return false;
}

int main(){
	Complex c1(3,4),c2(5,6),c3;
	cout<<"c1="<<c1.real<<"+j"<<c1.imag<<endl;
	cout<<"c2="<<c2.real<<"+j"<<c2.imag<<endl;
	c3=c1+c2;
	cout<<"c1+c2="<<c3.real<<"+j"<<c3.imag<<endl;
	c3=c1+6.5;
	cout<<"c1+6.5="<<c3.real<<"+j"<<c3.imag<<endl;
	if(c1==c2) cout<<"两个复数相等"<<endl;
	else cout<<"两个复数不相等"<<endl;
	return 0; 
}

运行结果:
c1=3+j4
c2=5+j6
c1+c2=8+j10
c1+6.5=9.5+j4
两个复数不相等

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值