c/c++入门教程 - 2.4.5 c++运算符重载(加号、左移、递增、赋值、关系、函数调用)

2023-11-08

目录

4.5 运算符重载

4.5.1 加号运算符重载

4.5.2 左移运算符重载

4.5.3 递增运算符重载

4.5.4 赋值运算符重载

4.5.5 关系运算符重载

4.5.6 函数调用运算符重载

相关教程


4.5 运算符重载

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

 

4.5.1 加号运算符重载

作用:实现两个自定义数据类型相加的运算。

operator+ 的简化写法就是 +。

  • 有三种重载方法:

1.成员函数重载+号,Person operator+(Person& p)

2.全局函数重载+号,Person operator+(Person& p1, Person& p2)

3.函数重载的版本,Person operator+(int num),Person operator+(Person& p1, int num)

  • 总结:

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

不要滥用运算符重载。

#include <iostream>
using namespace std;
#include <string>

class Person
{
public:

	int m_A;
	int m_B;

	// 通过自己写成员函数,实现两个对象相加属性后返回新的对象
	Person PersonAddPerson(Person& p)
	{
		Person temp;
		temp.m_A = this->m_A + p.m_A;
		temp.m_B = this->m_B + p.m_B;
		return temp;
	}

	// 编译器给起了一个通用的名称 operator+
	// 1.成员函数重载+号
	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;
	}

	 函数重载的版本
	//Person operator+(int num)
	//{
	//	Person temp;
	//	temp.m_A = this->m_A + num;
	//	temp.m_B = this->m_B + num;
	//	return temp;
	//}
};

 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 (void)
{
	Person p1;
	p1.m_A = 10;
	p1.m_B = 20;

	Person p2;
	p2.m_A = 30;
	p2.m_B = 40;

	Person p3 = p1.PersonAddPerson(p2);
	cout << "p3.m_A = " << p3.m_A << endl;
	cout << "p3.m_B = " << p3.m_B << endl << endl;

	// 成员函数重载本质调用
	Person p4 = p1.operator+(p2);

	// 全局函数重载本质调用
	//Person p4 = operator+(p1, p2);

	cout << "p4.m_A = " << p4.m_A << endl;
	cout << "p4.m_B = " << p4.m_B << endl << endl;

	// 简化形式
	Person p5 = p1 + p2;
	cout << "p5.m_A = " << p5.m_A << endl;
	cout << "p5.m_B = " << p5.m_B << endl << endl;

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

int main() {

	test01();

	system("pause");
	return 0;
}
-----------------------------------------------------------------------
p3.m_A = 40
p3.m_B = 60

p4.m_A = 40
p4.m_B = 60

p5.m_A = 40
p5.m_B = 60

p6.m_A = 110
p6.m_B = 120

请按任意键继续. . .

 

 

4.5.2 左移运算符重载

作用:可以输出自定义的类型。

 

形如 cout << a << endl;

利用成员函数  左移运算符  p.operator<<(cout)  简化版本  p << cout

不能利用成员函数重载<<运算符,因为无法实现 cout在左侧。

如果要达成 cout << 对象,由于类中的成员函数调用,对象只能在左侧,所以只能利用全局函数重载左移运算符。

#include <iostream>
using namespace std;
#include <string>

class Person
{
	friend ostream& operator<<(ostream& out, Person& p);

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

	int m_A;
	int m_B;
};

// 只能利用全局函数重载左移运算符
ostream& operator<<(ostream& out, Person& p)
{
	out << "m_A = " << p.m_A << "  m_B = " << p.m_B;
	return out;
}

void test01 (void)
{
	Person p1(10, 20);
	Person p2(30, 40);

	cout << p1 << endl << p2 << "Hello world!" << endl;
}

int main() {

	test01();

	system("pause");
	return 0;
}
--------------------------------------------------------------------
m_A = 10  m_B = 20
m_A = 30  m_B = 40Hello world!
请按任意键继续. . .

 

 

4.5.3 递增运算符重载

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

重载前置++运算符、后置++运算符。

总结:前置递增返回的是引用,后置递增返回的是值。

 

注意:ostream& operator<<(ostream& out, Person& p);

ostream& operator<<(ostream& out, Person p);他俩cout的输入参数不一样,用错了会报错。

 

前置递增重载:

#include <iostream>
using namespace std;
#include <string>

class Person
{
	friend ostream& operator<<(ostream& out, Person& p);
	//friend ostream& operator<<(ostream& out, Person p);

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

	// 重载前置++运算符  返回引用为了一直对一个数据进行递增操作
	Person& operator++()
	{
		m_A++;
		return *this;
	}

	// 重载后置++运算符
	Person operator++(int)	// int代表占位参数,可以用于区分前置和后置递增
	{
		Person temp = *this;
		m_A++;
		return temp;
	}

private:

	int m_A;
	int m_B;
};

// 只能利用全局函数重载左移运算符
ostream& operator<<(ostream& out, Person& p)
{
	out << "m_A = " << p.m_A << "  m_B = " << p.m_B;
	return out;
}

//ostream& operator<<(ostream& out, Person p)
//{
//	out << "m_A = " << p.m_A << "  m_B = " << p.m_B;
//	return out;
//}

void test01 (void)
{
	Person p1(10, 20);
	Person p2(30, 40);

	cout << ++p1 << endl << p2 << "Hello world!" << endl;
	cout << p1 << endl << endl;
}

//void test02()
//{
//	Person p1(10, 20);
//	cout << p1++ << endl;
//	cout << p1 << endl << endl;
//}

int main() {

	test01();
	//test02();

	system("pause");
	return 0;
}
---------------------------------------------------------------------------
m_A = 11  m_B = 20
m_A = 30  m_B = 40Hello world!
m_A = 11  m_B = 20

请按任意键继续. . .

 

后置递增的重载:

#include <iostream>
using namespace std;
#include <string>

class Person
{
	//friend ostream& operator<<(ostream& out, Person& p);
	friend ostream& operator<<(ostream& out, Person p);

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

	// 重载前置++运算符  返回引用为了一直对一个数据进行递增操作
	Person& operator++()
	{
		m_A++;
		return *this;
	}

	// 重载后置++运算符
	Person operator++(int)	// int代表占位参数,可以用于区分前置和后置递增
	{
		Person temp = *this;
		m_A++;
		return temp;
	}

private:

	int m_A;
	int m_B;
};

 只能利用全局函数重载左移运算符
//ostream& operator<<(ostream& out, Person& p)
//{
//	out << "m_A = " << p.m_A << "  m_B = " << p.m_B;
//	return out;
//}

ostream& operator<<(ostream& out, Person p)
{
	out << "m_A = " << p.m_A << "  m_B = " << p.m_B;
	return out;
}

void test01 (void)
{
	Person p1(10, 20);
	Person p2(30, 40);

	cout << ++p1 << endl << p2 << "Hello world!" << endl;
	cout << p1 << endl << endl;
}

void test02()
{
	Person p1(10, 20);
	cout << p1++ << endl;
	cout << p1 << endl << endl;
}

int main() {

	test01();
	test02();

	system("pause");
	return 0;
}
-----------------------------------------------------------------------
m_A = 11  m_B = 20
m_A = 30  m_B = 40Hello world!
m_A = 11  m_B = 20

m_A = 10  m_B = 20
m_A = 11  m_B = 20

请按任意键继续. . .

 

4.5.4 赋值运算符重载

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

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

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

 

注意:加了析构,释放堆区内存,但如果没有重载赋值运算符,程序会崩溃

return *this; 是为了可以形成 p1 = p2 = p3 链式结构。

#include <iostream>
using namespace std;
#include <string>

class Person
{

public:
	Person(int a)
	{
		m_A = new int(a);
	}
	
	~Person()
	{
		if (m_A != NULL)
		{
			delete m_A;
			m_A = NULL;
		}
	}

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

		// 先判断释放有属性在堆内存,如果有先释放干净,然后再深拷贝
		if (m_A != NULL)
		{
			delete m_A;
			m_A = NULL;
		}

		// 深拷贝
		m_A = new int(*p.m_A);

		// 返回对象本身
		return *this;
	}

	int *m_A;
};

void test01 (void)
{
	Person p1(10);
	Person p2(20);
	p2 = p1;

	Person p3(18);
	p1 = p2 = p3;

	cout << *p1.m_A << endl;
	cout << *p2.m_A << endl;
	cout << *p3.m_A << endl;
}

int main() {

	test01();

	system("pause");
	return 0;
}
---------------------------------------------------------------------
18
18
18
请按任意键继续. . .

 

4.5.5 关系运算符重载

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

示例:

#include <iostream>
using namespace std;
#include <string>

class Person
{

public:
	Person(string str, int age)
	{
		m_Name = str;
		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 (void)
{
	Person p1("XiaoMing", 18);
	Person p2("XiaoMing", 18);

	if (p1 == p2)
		cout << "p1 p2 相等" << endl;
	else cout << "p1 p2 不等" << endl;

	if (p1 != p2)
		cout << "p1 p2 不等" << endl;
	else cout << "p1 p2 相等" << endl;

}

int main() {

	test01();

	system("pause");
	return 0;
}
---------------------------------------------------------------------------
p1 p2 相等
p1 p2 相等
请按任意键继续. . .

 

4.5.6 函数调用运算符重载

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

class MyPrint
{

public:
	void operator()(string text)
	{
		cout << text << endl;
	}
};

void test01 (void)
{
	MyPrint myPrint;
	myPrint("Hello World!");
}

class MyAdd
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};

void test02()
{
	MyAdd myAdd;
	int ret = myAdd(100, 100);
	cout << "ret = " << ret << endl;

	// 匿名对象调用
	cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}

int main() {

	test01();
	test02();

	system("pause");
	return 0;
}
----------------------------------------------------------------------------
Hello World!
ret = 200
MyAdd()(100,100) = 200
请按任意键继续. . .

 

 

相关教程

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c/c++入门教程 - 2.4.5 c++运算符重载(加号、左移、递增、赋值、关系、函数调用) 的相关文章

  • 静态只读字符串数组

    我在我的 Web 应用程序中使用静态只读字符串数组 基本上数组有错误代码 我将所有类似的错误代码保存在一个数组中并检查该数组 而不是检查不同常量字符串中的每个错误代码 like public static readonly string m
  • 为什么在连接两个字符串时 Python 比 C 更快?

    目前我想比较 Python 和 C 用来处理字符串的速度 我认为 C 应该比 Python 提供更好的性能 然而 我得到了完全相反的结果 这是 C 程序 include
  • GetType() 在 Type 实例上返回什么?

    我在一些调试过程中遇到了这段代码 private bool HasBaseType Type type out Type baseType Type originalType type GetType baseType GetBaseTyp
  • IdentityServer 4 对它的工作原理感到困惑

    我阅读和观看了很多有关 Identity Server 4 的内容 但我仍然对它有点困惑 因为似乎有很多移动部件 我现在明白这是一个单独的项目 它处理用户身份验证 我仍然不明白的是用户如何注册它 谁存储用户名 密码 我打算进行此设置 Rea
  • 查找进程的完整路径

    我已经编写了 C 控制台应用程序 当我启动应用程序时 不使用cmd 我可以看到它列在任务管理器的进程列表中 现在我需要编写另一个应用程序 在其中我需要查找以前的应用程序是否正在运行 我知道应用程序名称和路径 所以我已将管理对象搜索器查询写入
  • 为什么在 WebApi 上下文中在 using 块中使用 HttpClient 是错误的?

    那么 问题是为什么在 using 块中使用 HttpClient 是错误的 但在 WebApi 上下文中呢 我一直在读这篇文章不要阻止异步代码 https blog stephencleary com 2012 07 dont block
  • 告诉 Nancy 将枚举序列化为字符串

    Nancy 默认情况下在生成 JSON 响应时将枚举序列化为整数 我需要将枚举序列化为字符串 有一种方法可以通过创建来自定义 Nancy 的 JSON 序列化JavaScript 原始转换器 https github com NancyFx
  • 启动时的 Excel 加载项

    我正在使用 Visual C 创建 Microsoft Excel 的加载项 当我第一次创建解决方案时 它包含一个名为 ThisAddIn Startup 的函数 我在这个函数中添加了以下代码 private void ThisAddIn
  • 如何在 Qt 应用程序中通过终端命令运行分离的应用程序?

    我想使用命令 cd opencv opencv 3 0 0 alpha samples cpp cpp example facedetect lena jpg 在 Qt 应用程序中按钮的 clicked 方法上运行 OpenCV 示例代码
  • IQueryable 单元或集成测试

    我有一个 Web api 并且公开了一个端点 如下所示 api 假期 name name 这是 Web api 的控制器 get 方法 public IQueryable
  • 在视口中查找 WPF 控件

    Updated 这可能是一个简单或复杂的问题 但在 wpf 中 我有一个列表框 我用一个填充数据模板从列表中 有没有办法找出特定的数据模板项位于视口中 即我已滚动到其位置并且可以查看 目前我连接到了 listbox ScrollChange
  • 在 NaN 情况下 to_string() 可以返回什么

    我使用 VS 2012 遇到了非常令人恼火的行为 有时我的浮点数是 NaN auto dbgHelp std to string myFloat dbgHelp最终包含5008角色 你不能发明这个东西 其中大部分为0 最终结果是 0 INF
  • 为什么这个二维指针表示法有效,而另一个则无效[重复]

    这个问题在这里已经有答案了 这里我编写了一段代码来打印 3x3 矩阵的对角线值之和 这里我必须将矩阵传递给函数 矩阵被传递给指针数组 代码可以工作 但问题是我必须编写参数的方式如下 int mat 3 以下导致程序崩溃 int mat 3
  • 高效列出目录中的所有子目录

    请参阅迄今为止所采取的建议的编辑 我正在尝试使用 WinAPI 和 C 列出给定目录中的所有目录 文件夹 现在我的算法又慢又低效 使用 FindFirstFileEx 打开我正在搜索的文件夹 然后我查看目录中的每个文件 使用 FindNex
  • 检测到严重错误 c0000374 - C++ dll 将已分配内存的指针返回到 C#

    我有一个 c dll 它为我的主 c 应用程序提供一些功能 在这里 我尝试读取一个文件 将其加载到内存 然后返回一些信息 例如加载数据的指针和内存块的计数到 c Dll 成功将文件读取到内存 但在返回主应用程序时 程序由于堆损坏而崩溃 检测
  • 在 Windows Phone silverlight 8.1 上接收 WNS 推送通知

    我有 Windows Phone 8 1 silverlight 应用程序 我想使用新框架 WNS 接收通知 我在 package appxmanifest 中有
  • 我可以在“字节数”设置为零的情况下调用 memcpy() 和 memmove() 吗?

    当我实际上没有什么可以移动 复制的时候 我是否需要处理这些情况memmove memcpy 作为边缘情况 int numberOfBytes if numberOfBytes 0 memmove dest source numberOfBy
  • 是否可以在不连接数据库的情况下检索 MetadataWorkspace?

    我正在编写一个需要遍历实体框架的测试库MetadataWorkspace对于给定的DbContext类型 但是 由于这是一个测试库 我宁愿不连接到数据库 它引入了测试环境中可能无法使用的依赖项 当我尝试获取参考时MetadataWorksp
  • 如何将十六进制字符串转换为无符号长整型?

    我有以下十六进制值 CString str str T FFF000 如何将其转换为unsigned long 您可以使用strtol作用于常规 C 字符串的函数 它使用指定的基数将字符串转换为 long long l strtol str
  • 不区分大小写的字符串比较 C++ [重复]

    这个问题在这里已经有答案了 我知道有一些方法可以进行忽略大小写的比较 其中涉及遍历字符串或一个good one https stackoverflow com questions 11635 case insensitive string

随机推荐