黑马-类与对象-运算符重载-笔记

文章展示了如何在C++中通过成员函数实现运算符重载,以Person类为例,重载了+运算符,既实现了两个Person对象的相加,也实现了Person对象与整数的相加。同时,文中提到运算符重载不应滥用,并给出了测试代码来验证运算符重载的效果。
摘要由CSDN通过智能技术生成

//运算符重载:
//赋予运算符新的作用
//注意事项:
//1、内置的数据类型的表达式的运算符不能改变
//2、不要滥用运算符

#include<iostream>
using namespace std;
class Person {
public:
	int m_a;
	int m_b;
	//成员函数实现运算符重载
	Person operator+(Person& p) {
		Person tmp;
		tmp.m_a = this->m_a + p.m_a;
		tmp.m_b = this->m_b + p.m_b;
		return tmp;
	}
};/*
Person operator+(Person& p1, Person& p2) {
	Person tmp;
	tmp.m_a = p1.m_a + p2.m_a;
	tmp.m_b = p1.m_b + p2.m_b;
	return tmp;
}*/
Person operator+(Person& p, int num) {
	Person tmp;
	tmp.m_a = p.m_a +num;
	tmp.m_b = p.m_b + num;
	return tmp;
}
void test01() {
	Person p1;
	p1.m_a = 10;
	p1.m_b = 10;
	Person p2;
	p2.m_a = 10;
	p2.m_b = 10;
	//本质是Person p3=p1.operator(p2);
	Person p3 = p1 + p2;
	cout << "p3,m_a=" << p3.m_a << endl;
	cout << "p3,m_b=" << p3.m_b << endl;
	//运算符重载也可以发生函数重载
	Person p4 = p1 + 100;
	cout << "p3,m_a=" << p4.m_a << endl;
	cout << "p3,m_b=" << p4.m_b << endl;
}
int main() {
	test01();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值