可调用对象:
1是一个函数指针
#include<iostream>
using namespace std;
void f(int num)
{cout << num << endl;
}using func = void(*)(int);int main()
{func i=f;i(12);return 0;
}
2具有operator()成员函数的仿函数
#include<iostream>
using namespace std;class test {
public:test(int num){cout << num << endl;}void operator()(int num){cout << "operator->" << num << endl;}};int main()
{test(1);test t(2);t(10);return 0;
}
3是一个可以转化为函数指针的类对象
#include<iostream>
using namespace std;void f(int num,string str)
{cout << "f(int num)->" << num <<str << endl;
}using func = void(*)(int,string);class test {
public:void operator()(int num){cout << "仿函数:operator()(int)->" << num << endl;}operator func() //将类对象转换为函数指针{//return hello; //报错,因为hello属于对象,然而我们现在没有创建对象return world; //world属于类}void hello(int num){cout << "hello(num)->" << num << endl;}static void world(int num,string str){cout << "world(num)->" << num << str << endl;}};int main()
{test t;t(10);test tt;tt(13,"lyh");return 0;
}
4是一个类成员函数指针或者类成员指针
#include<iostream>
using namespace std;class test {
public:int f(){cout << "f()" << endl;return 0;}int static g(){cout << "g()" << endl; return 0;}int age;string static name;
};string test::name = "ZJU";int main()
{test t;//定义类成员函数指针指向类非静态成员函数int(test::* x)() = &test::f; //法1(t.*x)(); //法1调用using func = int(test::*)(); //法2func i = &test::f; //法2定义(t.*i)(); //法2调用//定义类成员函数指针指向静态成员函数int(*y)() = &test::g; //法1y();using func2 = int(*)(); //法2func2 j = &test::g;j();//定义类成员指针指向类非静态成员int test::* a = &test::age; //法1 t.*a = 100;cout << t.age << endl;using s = int test::*; //法2s s1 = &test::age;t.*s1 = 1000;cout << t.age << endl;//定义类成员指针指向类静态成员 string* z = &test::name; //法1*z = "PKU";cout << test::name << endl;using z2 = string*; //法2z2 z22= &test::name;*z22 = "THU";cout << test::name << endl;return 0;
}