C++ 类成员函数 与函数指针

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值