C/C++教程

【【b站黑马程序员C++视频学习笔记-函数调用运算符重载】】

本文主要是介绍【【b站黑马程序员C++视频学习笔记-函数调用运算符重载】】,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

函数调用运算符重载

设计一个打印输出类,将()重载,打印输出字符串,注意要包含头文件<string.h>

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


//函数调用运算符重载

//打印输出类
class Myprint {
public:
	//重载函数调用运算符
	void operator()(string test) {
		cout << test << endl;
	}
};

void Myprint02(string test) {
	cout << test << endl;
}
void test01() {
	Myprint myprint;
	myprint("hello world");//由于使用起来类似于函数调用,所以也叫仿函数
	Myprint02("hello world");//这个是函数调用,而不是运算符重载
}

int main() {
	test01();
	system("pause");

	return 0;
}

其中,

	Myprint02("hello world")

这一段是调用了上面在类外定义的函数,与重载没有什么关系,但是二者都能打印输出hello world

仿函数是非常灵活的,还可以写出其他的,比如实现加法运算

//仿函数非常灵活,没有固定的写法
//加法类
class MyAdd
{
public:
	int operator()(int num1, int num2) {
		return num1 + num2;
	}
};

void test02() {
	MyAdd myadd;
	int ret = myadd(50, 60);
	cout << "ret= " << ret << endl;
}

调用test02()就可以输出两个数相加的结果110

注:在test02()中,也可以直接使用匿名函数对象

void test02() {


	//匿名函数对象
	cout << MyAdd()(100, 100) << endl;
}

这样也可以输出正确的结果

这篇关于【【b站黑马程序员C++视频学习笔记-函数调用运算符重载】】的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!