【C++学习笔记】 4-1 运算符重载—基本概念


1. 运算符


在这里插入图片描述


2. 自定义数据类型与运算符重载


在这里插入图片描述


3. 运算符重载


在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述


4. 运算符重载为普通函数


class Complex{
	public:
		Complex(double r = 0.0, double i = 0.0){
			real = r;
			imaginary = i;
		}
		double real;      //real part
		double imaginary; //imaginary part
};
Complex operator+ (const Complex & a, const Complex & b)
{
	return Complex(a.real + b.real, a.imaginary + b.imaginary);
}//"类名(参数表)"就代表一个对象

Complex a(1,2), b(2, 3), c;
c = a + b;//相当于什么?

重载为普通函数时,参数个数为运算符目数


5. 运算符重载为成员函数


class Complex{
	public:
		Complex(double r = 0.0, double m = 0.0):
			real(r), imaginary(m){ }    //constructor
		Complex operator+(const Complex &); //addition
		Complex operator-(const Complex &); //subtraction
	private:
		double real;      //real part
		double imaginary; //imaginary part
};
//Overloaded addition operator
Complex Complex::operator+(const Complex & operand2){
	return Complex(real + operand2.real,
			imaginary + operand2.imaginary);
}
//Overloaded subtraction operator
Complex Complex::operator-(const Complex & operand2){
	return Complex(real - operand2.real,
   			imaginary - operand2.imaginary);
}
int main(){
	Complex x, y(4.3, 8.2), z(3.3, 1.1);
	x = y + z;
	x = y - Z;
	return 0;
}

重载为成员函数时,参数个数为运算符数目减一



站在巨人的肩上
【1】北京大学信息技术学院《程序设计实习》

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

智驾

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值