当前位置: 首页 > news >正文

黑马C++ 02 核心5 —— 类和对象_运算符重载(重难点)

文章目录

  • 01 运算符重载(成员函数或者全局函数重载)
    • 1.1 加号运算符重载
      • 成员函数重载 +
      • 全局函数重载 +
      • 函数重载 +(重点)
    • 1.2 左移运算符重载(可输出自定义数据类型)
    • 1.3 递增运算符重载(自己定义自增自减)
      • 重载前置 ++ 运算符(返回的是引用)
      • 重载后置 ++ 运算符(返回的是值) !!!重点
    • 1.4 赋值运算符
    • 1.5 关系运算符重载
      • 重载 == 号
      • 重载 != 号
    • 1.6 函数调用运算符重载(仿函数)

运算符重载概念: 对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

01 运算符重载(成员函数或者全局函数重载)

1.1 加号运算符重载

在这里插入图片描述
上述是无法实现相加

  • 通过自己写两个成员函数,实现两个对象相加属性后返回新的对象
  • 自身对象的A属性 + 传进来的对象的A属性 再赋值给新的对象
    在这里插入图片描述
  • 编译器给取了一个通用名称
  • 同过成员函数重载+号
    在这里插入图片描述
  • 通过全局函数重载+
    在这里插入图片描述
  • 结果

在这里插入图片描述

成员函数重载 +

class Person
{
public:
	// 方式1、成员函数重载+号, this指的是正在调用的对象
	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;
};

// 成员函数重载本质调用,这里this指向的就是p1
Person p2 = p0.operator+(p1);

全局函数重载 +

// 方式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 p3 = operator+(p1, p2);
//Person p3 = p0 + p1;// 全局函数重载和成员函数重载均可以使用这种方式

函数重载 +(重点)

函数重载满足条件:

  • 同一个作用域(比如都是成员函数)
  • 函数名一样operator
  • 参数不一样,个数,类型,顺序不一样
  • 返回值不作为重载条件
// 函数重载+
Person operator+(Person& p1, int num)
{
	Person temp;
	temp.m_A = p1.m_A + num;
	temp.m_B = p1.m_B + num;
	return temp;
}

// 运算符重载也可以发生函数重载
Person p4 = p0 + 100;//Person + int
#include<iostream>
using namespace std;

// 加号运算符重载

class Person
{
public:
	// 方式1、成员函数重载+号, this指的是正在调用的对象
	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;
};

// 方式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 num)
{
	Person temp;
	temp.m_A = p1.m_A + num;
	temp.m_B = p1.m_B + num;
	return temp;
}

void test01()
{
	Person p0;
	p0.m_A = 10;
	p0.m_B = 10;
	Person p1;
	p1.m_A = 20;
	p1.m_B = 20;

	// 成员函数重载本质调用,这里this指向的就是p0
	Person p2 = p0.operator+(p1);
	cout << "p2.m_A = " << p2.m_A << endl;
	cout << "p2.m_B = " << p2.m_B << endl;

	// 全局函数重载本质调用
	Person p3 = operator+(p0, p1);
	//Person p3 = p0 + p1;// 全局函数重载和成员函数重载均可以使用这种方式
	cout << "p3.m_A = " << p3.m_A << endl;
	cout << "p3.m_B = " << p3.m_B << endl;

	// 运算符重载也可以发生函数重载
	Person p4 = p0 + 100;// Person + int
	cout << "p4.m_A = " << p4.m_A << endl;
	cout << "p4.m_B = " << p4.m_B << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

在这里插入图片描述

总结1:对于内置的数据类型的表达式的的运算符是不可能改变的

总结2:不要滥用运算符重载

1.2 左移运算符重载(可输出自定义数据类型)

  • 作用:可以输出自定义数据类型
  • p.operator<<(cout) 简化版本 p << cout,通常不会用成员函数重载<<运算符,因为无法实现 cout 在左侧
  • 只能利用全局函数重载左移运算符
  • cout 是类ostream的对象,就是标准输出流的对象,且全局只能有一个,用引用的方式传递
  • 本质 operator << (cout,p) 简化cout << p; cout数据类型是ostream(输出流)
#include<iostream>
using namespace std;

//左移运算符重载——可以输出自定义数据类型
//重载左移运算符配合友元可以实现输出自定义数据类型

class Person
{
	// 作为person类的好朋友,访问私有内容
	friend ostream& operator << (ostream& cout, Person& p);

public:
	Person(int a, int b)
	{
		m_A = a;
		m_B = b;
	}

private:

	// 左移运算符只有一个对象
	// 利用成员函数重载 左移运算符(不知道先返回什么,就写一个void) 
	// p.operator<<(cout) 简化版本 p << cout
	// 通常不会用成员函数重载<<运算符,因为无法实现 cout 在左侧
	/*void operator<<(Person& p)
	{
	}*/

	int m_A;
	int m_B;
};

// 只能利用全局函数重载左移运算符
// cout是类ostream的对象,就是标准输出流的对象,且全局只能有一个,用引用方式传递
// 本质 operator << (cout,p) 简化cout << p; cout数据类型是ostream(输出流)
ostream& operator << (ostream& cout, Person& p)
{
	cout << "m_A = " << p.m_A << " m_B = " << p.m_B << endl;
	return cout;// 解引用ostream,返回cout,可以无限往后追加输入
}

void test01()
{
	// 方式1
	// Person p;
	// p.m_A = 10;
	// p.m_B = 10;
	// cout << p.m_A << endl;
	// cout << p.m_B << endl;

	// 方式2
	Person p(10, 10);
	cout << p << "hello " << endl;// 可以输出p
}

int main()
{
	test01();

	system("pause");
	return 0;
}

在这里插入图片描述

  • 总结:重载左移运算符配合友元可以实现输出自定义数据类型

1.3 递增运算符重载(自己定义自增自减)

  • 作用: 通过重载递增运算符,实现自己的整型数据

在这里插入图片描述

  • this指向自身,返回引用 *this

重载前置 ++ 运算符(返回的是引用)

	// 返回引用是为了一直对一个数据进行递增操作
	MyInteger& operator++()
	{
		// 先进行 ++ 运算
		m_Num++;

		// 再将自身做返回
		return *this;// this指向自身,返回引用
	}

重载后置 ++ 运算符(返回的是值) !!!重点

  • 如果加入返回的是引用,由于返回的是局部的对象的引用,局部对象在当前函数(MyInteger temp = *this)执行完之后就会释放,继续返回引用(return temp)就是非法操作。
	// 先记录当时的结果
	MyInteger temp = *this;//*this表示自身,记录自身结果
	// 后递增
	m_Num++;
	// 最后将记录结果做返回
	return temp;
    // void operator++(int) int代表占位参数,可以区分前置和后置递增
	// MyInteger&表示返回局部对象的引用,temp是局部变量,返回局部对象的引用
	// 局部对象在当前函数结束后就被释放,继续返回引用为非法操作
	MyInteger operator++(int)// 返回值不可以作为重载的条件,返回的是值
	{
		// 先记录当时的结果
		MyInteger temp = *this;//*this表示自身,记录自身结果
		// 后递增
		m_Num++;
		// 最后将记录结果做返回
		return temp;
	}
#include<iostream>
using namespace std;

//重载递增运算符

//自定义整型
class MyInteger
{
	friend ostream& operator<<(ostream& cout, MyInteger myint);

public:
	MyInteger()
	{
		m_Num = 0;
	}

	// 重载前置 ++ 运算符(返回的是引用)
	// 返回引用是为了一直对一个数据进行递增操作
	MyInteger& operator++()
	{
		// 先进行 ++ 运算
		m_Num++;

		// 再将自身做返回
		return *this;// this指向自身,返回引用
	}

	// 重载后置 ++ 运算符(返回的是值)
	// void operator++(int) int代表占位参数,可以区分前置和后置递增
	// MyInteger&表示返回局部对象的引用,temp是局部变量,返回局部对象的引用
	// 局部对象在当前函数结束后就被释放,继续返回引用为非法操作
	MyInteger operator++(int)// 返回值不可以作为重载的条件,返回的是值
	{
		// 先记录当时的结果
		MyInteger temp = *this;//*this表示自身,记录自身结果
		// 如果加入返回的是引用,由于返回的是局部的对象的引用,局部对象在当前函数执行完之后就会释放
		// 继续返回引用就是非法操作
		// 后递增
		m_Num++;
		// 最后将记录结果做返回
		return temp;
	}

private:
	int m_Num;
};

// 利用全局运算符重载左移运算符   重载 << 运算符
ostream& operator<<(ostream& cout, MyInteger myint)
{
	cout << myint.m_Num;// m_Num 私有化
	return cout;
}

void test01()
{
	MyInteger myint;

	cout << ++myint << endl;
}

void test02()
{
	MyInteger myint;

	cout << myint++ << endl;
}

int main()
{
	test01();
	test02();

	system("pause");
	return 0;
}

1.4 赋值运算符

C++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝
  4. 赋值运算符 operator=, 对属性进行值拷贝

如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

  • 编译系统提供的等号赋值操作,是浅拷贝,p2先执行右边的析构代码,先判断是否为空,不为空,释放堆区内存。p1再执行右边的析构代码,判断p1是否为空,也不为空,释放相同的堆区内存,导致堆区的内存重复释放,导致奔溃。
    在这里插入图片描述
  • 解决方法:使用深拷贝,使p2和p1分别指向不同的堆区内存

在这里插入图片描述

#include<iostream>
using namespace std;

class Person
{
public:

	Person(int age)
	{
		// 将年龄数据开辟到堆区
		m_Age = new int(age);// new int 返回的是int*,
	}

	// 重载赋值运算符 
	Person& operator=(Person& p)
	{
		// 编译器提供的代码是浅拷贝
		// m_Age = p.m_Age;

		// 先判断是否有属性在堆区,如果有,先释放干净,然后再深拷贝
		if (m_Age != NULL)
		{
			delete m_Age;
			m_Age = NULL;
		}
		
		// 提供深拷贝 解决浅拷贝的问题
		m_Age = new int(*p.m_Age);// new一个int类型空间

		// 返回自身
		return *this;
	}

	// 析构函数 堆区的数据要手动释放 —— 有数字就释放
	~Person()
	{
		if (m_Age != NULL)
		{
			delete m_Age;
			m_Age = NULL;
		}
	}

	// 年龄的指针
	int* m_Age;
};


void test01()
{
	Person p1(18);
	Person p2(20);
	Person p3(30);

	p3 = p2 = p1; // 赋值操作

	cout << "p1的年龄为:" << *p1.m_Age << endl;
	cout << "p2的年龄为:" << *p2.m_Age << endl;
	cout << "p3的年龄为:" << *p3.m_Age << endl;
}

int main() {

	test01();
	system("pause");
	return 0;
}

1.5 关系运算符重载

  • **作用:**重载关系运算符,可以让两个自定义类型对象进行对比操作

重载 == 号

bool operator==(Person& p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

重载 != 号

bool operator!=(Person& p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
#include<iostream>
using namespace std;

class Person
{
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	};

	// 重载 == 号
	bool operator==(Person& p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	// 重载 != 号
	bool operator!=(Person& p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

	string m_Name;
	int m_Age;
};

void test01()
{
	//int a = 0;
	//int b = 0;

	Person a("孙悟空", 18);
	Person b("孙悟空", 18);

	if (a == b)
	{
		cout << "a 和 b 相等" << endl;
	}
	else
	{
		cout << "a 和 b 不相等" << endl;
	}

	Person c("孙悟空", 18);
	Person d("孙悟空", 20);

	if (c != d)
	{
		cout << "c 和 d 不相等" << endl;
	}
	else
	{
		cout << "c 和 d 相等" << endl;
	}
}

int main()
{
	test01();

	system("pause");
	return 0;
}

在这里插入图片描述

1.6 函数调用运算符重载(仿函数)

  • 函数调用运算符 () 也可以重载
  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  • 仿函数没有固定写法,非常灵活
#include<iostream>
using namespace std;
#include<string>

// 函数调用运算符重载

// 打印输出类
class MyPrint
{
public:
	void operator()(string text)// 重载()操作符
	{
		cout << text << endl;
	}
};

void MyPrint02(string test)
{
	cout << test << endl;
}

void test01()
{
	// 重载函数调用运算符
	MyPrint myFunc;
	// 由于使用起来非常类似于函数调用,因此称为仿函数
	myFunc("hello world");
	
	// 函数调用
	MyPrint02("hello!");
}

// 仿函数非常灵活,没有固定的手法
// 加法类
class MyAdd
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};
void test02()
{
	MyAdd add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;

	//匿名函数对象 —— 匿名对象 有重载小括号
	cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}

int main() {

	test01();
	test02();

	system("pause");
	return 0;
}

在这里插入图片描述

相关文章:

  • 移动办公平台迎来定制潮,WorkPlus如何在钉钉和企微光环下 “出圈”?
  • Keras - ModelCheckpoint
  • 【零基础学Python】Day10 Python解释器
  • 搭建网课查题搜题公众号
  • Nginx的rewrite
  • redux入门详解
  • WRF学习笔记之三:使用ERA5数据驱动并运行WRFV4.4(一层嵌套)/WRF运行实录/WRF报错(踩坑)记录
  • PaddleOCR 2.6 编译详细步骤 + 踩坑记录(C++ GPU版)
  • 利尔达携手紫光展锐重磅发布5G R16模组,领跑5G To B新纪元
  • GD32F103ZET6奋斗者开发板W5500通信——01 基础移植
  • 智芯传感推出新型医疗级侵入式压力传感器ZXPA
  • 三节锂电升压充电芯片 CS5095EA 特点及应用
  • 网络协议:HTTPS
  • C++不定参数函数实现方式
  • js 类型及检测方式
  • 「译」Node.js Streams 基础
  • 【刷算法】求1+2+3+...+n
  • Brief introduction of how to 'Call, Apply and Bind'
  • co.js - 让异步代码同步化
  • Git 使用集
  • LeetCode29.两数相除 JavaScript
  • Magento 1.x 中文订单打印乱码
  • Python十分钟制作属于你自己的个性logo
  • React 快速上手 - 06 容器组件、展示组件、操作组件
  • RxJS: 简单入门
  • Work@Alibaba 阿里巴巴的企业应用构建之路
  • 基于MaxCompute打造轻盈的人人车移动端数据平台
  • 如何在 Tornado 中实现 Middleware
  • 用element的upload组件实现多图片上传和压缩
  • 机器人开始自主学习,是人类福祉,还是定时炸弹? ...
  • 积累各种好的链接
  • 说说我为什么看好Spring Cloud Alibaba
  • ​直流电和交流电有什么区别为什么这个时候又要变成直流电呢?交流转换到直流(整流器)直流变交流(逆变器)​
  • ​中南建设2022年半年报“韧”字当头,经营性现金流持续为正​
  • #HarmonyOS:软件安装window和mac预览Hello World
  • #mysql 8.0 踩坑日记
  • $Django python中使用redis, django中使用(封装了),redis开启事务(管道)
  • (175)FPGA门控时钟技术
  • (day 2)JavaScript学习笔记(基础之变量、常量和注释)
  • (附源码)springboot电竞专题网站 毕业设计 641314
  • (附源码)springboot建达集团公司平台 毕业设计 141538
  • (论文阅读23/100)Hierarchical Convolutional Features for Visual Tracking
  • (四) 虚拟摄像头vivi体验
  • (四)JPA - JQPL 实现增删改查
  • (四)模仿学习-完成后台管理页面查询
  • (转)Mysql的优化设置
  • (转)关于多人操作数据的处理策略
  • (转)使用VMware vSphere标准交换机设置网络连接
  • *Algs4-1.5.25随机网格的倍率测试-(未读懂题)
  • .net web项目 调用webService
  • .NET 事件模型教程(二)
  • .NET微信公众号开发-2.0创建自定义菜单
  • @Autowired 与@Resource的区别
  • [ vulhub漏洞复现篇 ] JBOSS AS 4.x以下反序列化远程代码执行漏洞CVE-2017-7504
  • [ACM] hdu 1201 18岁生日