运算符重载概念
对已经有的运算符进行定义,赋予另一种功能,以适应不同数据类型
加号运算符重载
作用:实现两个自定义数据类型相加的运算
- 注意实现形式
1.成员函数重载
2.全局函数重载
3.函数重载版本
#include<iostream>
#include<string>
using namespace std;
class Persion
{
public :
//成员函数重载
/*Persion operator+(Persion &p)
{
Persion temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}*/
int m_A;
int m_B;
};
//全局函数重载
Persion operator+(Persion &p1, Persion &p2) {
Persion temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B =p1.m_B + p2.m_B;
return temp;
}
//函数重载版本
Persion operator+(Persion &p1, int num) {
Persion temp;
temp.m_A = p1.m_A + num;
temp.m_B = p1.m_B + num;
return temp;
}
void test01() {
Persion p1;
p1.m_A = 10;
p1.m_B = 10;
Persion p2;
p2.m_A = 10;
p2.m_B = 10;
//1.成语函数重载本质调

本文介绍了C++的运算符重载,特别是加法运算符的重载,包括成员函数和全局函数两种重载方式,强调了运算符重载的适用性和注意事项。

1万+

被折叠的 条评论
为什么被折叠?



