在C++中存在"可调用对象"这么一个概念,准确来说,可调用对象有如下几种定义:
1.是一个函数指针
代码如下:
int print(int a, double b)
{cout << a << b << endl;return 0;
}int(*func)(int, double) = &print;
2.是一个具有operator()成员函数的类对象(仿函数)
代码如下:
#include <vector>
#include <iostream>
#include <string>using namespace std;using func_ptr = void(*)(int, string);struct Test
{void operator()(int x){cout << "x = " << x << endl;}
};int main()
{Test t1;t1(19);return 0;
}
测试结果:
3.是一个可被转换为函数指针的类对象
代码如下:
#include <vector>
#include <iostream>
#include <string>using namespace std;using func_ptr = void(*)(int, string);struct Test
{static void print(int a, string b){cout << "name = " << b << ",age = " << a << endl;}//将类对象转换成函数指针operator func_ptr(){return print;//需要是静态函数}
};int main()
{Test t1;t1(19, "nihao");return 0;
}
测试结果:
4.是一个类成员函数指针或者类成员指针
代码如下:
#include <vector>
#include <iostream>
#include <string>using namespace std;using funcptr = void(*)(int, string);struct Test
{static void print(int a, string b){cout << "name = " << b << ",age = " << a << endl;}void hello(int a, string b){cout << "name = " << b << ",age = " << a << endl;}int id = 520;};int main()
{Test t1;funcptr f = Test::print;//类的函数指针using fptr = void(Test::*)(int, string);fptr f1 = &Test::hello;//类的成员指针(变量)using ptr1 = int Test::*;ptr1 pt = &Test::id;Test ttt;(ttt.*f1)(20, "tom");ttt.*pt = 100;cout << "id = " << ttt.id << endl;return 0;
}
测试结果: