# day-06 类和对象–C++运算符重载--函数调用运算符重载

类和对象–C++运算符重载

C++ 预定义的运算符,只能用于基本数据类型的运算,不能用于对象的运算
如何使运算符能用于对象之间的运算呢

函数调用运算符重载

函数调用运算符 () 的重载
由于重载后使用的方式非常像函数的调用,因此称为仿函数,仿函数在STL中用得比较多

自定义打印函数

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

class MyPrint{
    
    
public:
	void operator()(string myprint){
    
    
		cout << myprint << endl;
	}
};
void test(){
    
    
	MyPrint myprint;//实例化一个对象
	myprint("hello world");
}

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

运行结果:
在这里插入图片描述

将实例化对象的参数传到仿函数内
在这里插入图片描述

自定义加法函数

#include <iostream>
using namespace std;

class MyAdd{
    
    
public:
	int operator()(int num1, int num2){
    
    
		return num1 + num2;
	}
};

void test(){
    
    
	MyAdd add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;

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

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

运行结果:
在这里插入图片描述

将实例化对象的参数传到仿函数内

在这里插入图片描述

因为仿函数既可以是int 又可以是void,还可以是其他的,即 仿函数没有固定写法,非常灵活

猜你喜欢

转载自blog.csdn.net/weixin_48245161/article/details/113108596