C++ 成员函数指针简单测试

class Dog
{
public:
    void Update_Func(short i);
    short (Dog::*pfunc)(short);
    std::function<short(short)> ffunc;
public:
    short goodMorning(short id);
    short goodAfternoon(short id);
};

void Dog::Update_Func(short i)
{
    switch (i)
    {
    case 1:
        pfunc = &Dog::goodMorning;
        ffunc = std::bind(&Dog::goodMorning, this, std::placeholders::_1);
        break;
    case 2:
        pfunc = &Dog::goodAfternoon;
        ffunc = std::bind(&Dog::goodAfternoon, this, std::placeholders::_1);
        break;
    }
}

short Dog::goodMorning(short id)
{
    return id + 1;
}

short Dog::goodAfternoon(short id)
{
    return id + 10;
}


int main()
{
    Dog dog;
    dog.Update_Func(1);
    auto res = (dog.*(dog.pfunc))(10);
    //auto res = (dog.*pfunc)(1);  // 这样是不行的,如果放在类外是可以的。
    cout << res << endl;

    short (Dog::*p)(short);
    p = &Dog::goodAfternoon;
    res = (dog.*p)(10);  // 放在类外,这样调用是可以的。
    cout << res << endl;

    /*用 function 应该是直接可以的*/

    res = dog.ffunc(10);
    cout << res << endl;
    dog.Update_Func(2);
    res = dog.ffunc(10);
    cout << res << endl;

    system("pause");
    return EXIT_SUCCESS;
}

输出:

11
20
11
20

如果成员函数指针放在类外,或用 function 绑定,goodMorninggoodAfternoon 两个函数必须是 public 外部可访问的。 如果是类内部成员函数指针,goodMorninggoodAfternoon 这两个函数可以是私有的。

posted @   double64  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-09-16 C# 转义字符
2021-09-16 C# base 和 this 在构造函数中的运用
2021-09-16 C# base 调用基类方法
点击右上角即可分享
微信分享提示