You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

尝试将const类成员函数指针赋值给std::array时遇编译错误求解决

编译错误解决:const成员函数指针赋值给数组的问题

错误原因

你定义的数组arr元素类型是普通函数指针bool (*)(int),但&S::foo是const成员函数指针bool (S::*)(int) const——这两种类型完全不兼容:

  • 普通函数指针直接指向函数地址,调用时不需要对象实例
  • 成员函数指针需要绑定类的实例才能调用,且带const限定的成员函数指针有专门的类型标识

解决方案1:修正数组元素为const成员函数指针

把数组的元素类型改成对应const成员函数指针的类型,调用时通过类实例(这里用this)来触发调用:

#include <iostream>
#include <array>

struct S
{
    // 修正数组元素类型为S的const成员函数指针
    std::array<bool (S::*)(int) const, 2> arr;

    bool foo(int a) const
    { 
        std::cout << a << std::endl; 
        return true;
    }

    bool foo2(int b) const
    { 
        std::cout << b << std::endl; 
        return true;
    }

    S()
    {
        arr[0] = &S::foo;              // 类型匹配,编译通过
        arr[1] = &S::foo2;             // 类型匹配,编译通过

        // 用this->*调用成员函数指针,括号不可省略(优先级问题)
        const bool res1 = (this->*arr[0])(6); 
        const bool res2 = (this->*arr[1])(7); 
    }
};

int main()
{
    S s;
    return 0;
}

解决方案2:改用静态成员函数(限无需访问实例成员的场景)

如果你的foo/foo2不需要访问类的非静态成员变量或函数,可以把它们改成静态成员函数,这样就能直接赋值给普通函数指针:

#include <iostream>
#include <array>

struct S
{
    std::array<bool (*)(int), 2> arr;

    // 改为静态成员函数
    static bool foo(int a)
    { 
        std::cout << a << std::endl; 
        return true;
    }

    static bool foo2(int b)
    { 
        std::cout << b << std::endl; 
        return true;
    }

    S()
    {
        arr[0] = &S::foo;              // 静态成员函数可直接赋值给普通函数指针
        arr[1] = &S::foo2;             // 类型匹配

        const bool res1 = arr[0](6); // 直接调用,无需实例
        const bool res2 = arr[1](7); 
    }
};

int main()
{
    S s;
    return 0;
}

注意:静态成员函数无法访问类的非静态成员,若你的业务逻辑需要访问实例数据,优先使用方案1。

内容的提问来源于stack exchange,提问作者rare77

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 09:35:24