前言
软件为visual studio2017,内容为C++学习笔记,以及相关的问题处理方法,目的是方便回顾和复习。
笔记来自于:黑马程序员C++教程。
一、运算符重载概念
运算符重载概念
:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。
二、加号运算符重载
1.加号运算符重载作用
- 作用:实现两个自定义数据类型相加的运算。
2.伪代码介绍
3.代码示例
# include <iostream>
using namespace std;
#include <string>
//+号运算符重载,
//1、成员函数重载+号
class Person {
public:
//成员函数重载
/*Person operator+(Person &p) {
Person 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;
};
void test01() {
Person p1;
p1.m_A = 10;
p1.m_B = 10;
Person p2;
p2.m_A = 20;
p2.m_B = 20;
//Person p3 = p1 + p2;//没有对+号进行重载。
Person p3;
p3 = p1.operator+(p2);
cout << "p3.m_A = " << p3.m_A << "p3.m_B = " << p3.m_B << endl;
}
//2、全局函数重载+号
Person operator+(Person &p1,Person &p2) {
Person temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p1.m_B + p2.m_B;
return temp;
};
//对运算符函数进行重载,返回值和函数名相同,但是其参数不同。
Person operator+(Person &p1, int a) {
Person temp;
temp.m_A = p1.m_A + a;
temp.m_B = p1.m_B + a;
return temp;
}
void test02() {
Person p1;
p1.m_A = 15;
p1.m_B = 20;
Person p2;
p2.m_A = 15;
p2.m_B = 20;
Person p3;
//成员函数重载本质调用
//p3 = p1.operator+(p2);
//全局函数重载本质调用
//p3 = operator+(p1, p2);
p3 = p1+p2;
//运算符重载也可以发生函数重载
Person p4;
p4 = p1 + 20;//相当于operator+(p1,20);
cout << "p3.m_A = " << p3.m_A << "p3.m_B = " << p3.m_B << endl;
cout << "p4.m_A = " << p4.m_A << "p4.m_B = " << p4.m_B << endl;
};
int main() {
//test01();
test02();
system("pause");
return 0;
}
4.小结
总结1
:对于内置的数据类型的表达式的运算符是不可能改变的。总结2
:不要滥用运算符重载。
三、左移运算符重载
1.作用
- 可以输出自定义的数据类型。