C++ 类成员函数 与函数指针
#include <iostream>
#include <memory>
class Person{
public:
Person(int v):value(v) {
// std::cout<<value<<std::endl;
}
int func1() {
std::cout<<"getValue"<<std::endl;
return 1;
}
static int func2(){
std::cout<<"static func"<<std::endl;
return 2;
}
void pfunc1(int (Person::*nonstatic)()){
std::cout<<"call pfunc1"<<std::endl;
}
void pfunc2(int(*p)()){
std::cout<<"call pfunc2"<<std::endl;
}
private:
int value;
};
typedef int (Person::*FuncPtr)();//定义一个函数指针 返回值int 函数参数为空 类成员非静态成员函数的函数指针
typedef int (*StaticFuncPtr)();//定义一个函数指针 返回值int 函数参数为空 类成员静态成员函数的函数指针
int main(int argc,char** argv)//
{
// std::unique_ptr<Person> person(new Person(5));
//用智能指针会报错no match for ‘operator->*’ (operand types are ‘std::unique_ptr<Person>’ and ‘FuncPtr {aka int (Person::*)()}’)
Person* person=new Person(5);
//成员非静态函数指针调用
FuncPtr nonstatic_ptr=&Person::func1;
std::cout<<(person->*nonstatic_ptr)()<<std::endl;//1
//成员静态函数指针调用
StaticFuncPtr static_ptr=&Person::func2;
std::cout<<static_ptr()<<std::endl;
// 通过 pFun1 只能调用静态方法
person->pfunc2(&Person::func2);
// 通过 pFun2 就是调用成员方法
person->pfunc1(&Person::func1);
// person->pfunc1(&Person::func2);//error
delete person;
return 0;
}
输出
getValue
1
static func
2
call pfunc2
call pfunc1