11.5.6重学C++之【函数调用运算符重载--仿函数】
#include<stdlib.h>#include<iostream>#include<string>using namespace std;/*4.5.6 函数调用运算符重载函数调用运算符()也可以重载由于重载后使用的方式很像函数的调用,故也称为仿函数仿函数没有固定写法,很灵活*/class MyPrint{public:void operator()(st
·
#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;
/*
4.5.6 函数调用运算符重载
函数调用运算符()也可以重载
由于重载后使用的方式很像函数的调用,故也称为仿函数
仿函数没有固定写法,很灵活
*/
class MyPrint{
public:
void operator()(string test){
cout << test << endl;
}
};
void myprint(string test){
cout << test << endl;
}
void test1(){
MyPrint mp;
mp("helloworld"); // 仿函数
myprint("helloworld"); // 函数调用
}
class MyAdd{
public:
int operator()(int num1, int num2){
return num1+num2;
}
};
void test2(){
MyAdd ma;
int sum = ma(10,20);
cout << sum << endl;
cout << MyAdd()(100, 100) << endl; // MyAdd()匿名函数对象,(100, 100)仿函数
}
int main()
{
test1();
test2();
system("pause");
return 0;
}
更多推荐
所有评论(0)