【C++】运算符重载
文章目录
前言
本篇文章将讲到运算符重载,加号运算符重载,左移运算符重载,递增运算符重载,指针运算符重载,赋值运算符重载,[ ]运算符重载,关系运算符重载,函数调用运算符重载, 以及不要重载&& 和 || 和重载建议。
一、加号运算符重载
对于内置的数据类型,编译器知道如何进行运算
但是对于自定义数据类型,编译器不知道如何运算
利用运算符重载 可以让符号有新的含义
利用加号重载 实现p1 + p2 Person数据类型相加操作
利用成员函数 和 全局函数 都可以实现重载
关键字 operator +
成员本质 p1.operator+(p2)
全局本质 operator+(p1,p2)
简化 p1 + p2
运算符重载 也可以发生函数重载
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Person
{
public:
Person() {
};
Person(int a, int b) :m_A(a), m_B(b) {
};
//利用成员函数实现加号运算符重载
/*Person operator+(Person& p)
{
this->m_A += p.m_A;
this->m_B += p.m_B;
return *this;
}*/
int m_A;
int m_B;
};
//利用全局函数实现加号运算符重载
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 num)
{
Person temp;
temp.m_A = p1.m_A + num;
temp.m_B = p1.m_B + num;
return temp;
}
void test01()
{
Person p1(10, 20);
Person p2(20, 30);
Person p3 = p1 + p2;
//Person p3 = operator+(p1, p2); //全局函数本质
//Person p3 = p1.operator+(p2); //成员函数本质
cout << "p3.m_A = " << p3.m_A << " p3.m_B = " << p3.m_B << endl;
Person p4 = p1 + 10;
cout << "p4.m_A = " << p4.m_A << " p4.m_B = " << p4.m_B << endl;
//运算符重载 可不可以发生 函数重载? 可以
//p1 + 10;
}
int main() {
test01();
system("pause");
return EXIT_SUCCESS;
}
二、左移运算符重载
不要滥用运算符重载,除非有需求
不能对内置数据类型进行重载
对于自定义数据类型,不可以直接用 cout << 输出
需要重载 左移运算符
如果利用成员 函数重载 ,无法实现让cout 在左侧,因此不用成员重载
利用全局函数 实现左移运算符重载
ostream& operator<<(ostream &cout, Person & p1)
如果想访问类中私有内存,可以配置友元实现
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Person
{
friend ostream& operator<<(ostream& out, Person& p);
public:
Person(int a, int b)
{
this->m_A = a;
this->m_B = b;
}
//试图利用成员函数 做<<重载
//void operator<<( Person & p) // p.operator<<(cout) p<<cout
//{
//
//}
private:
int m_A;
int m_B;
};
//利用全局函数 实现左移运算符重载
ostream& operator<<(ostream&</