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

C++:如何正确初始化指向静态成员函数的指针静态数组

静态函数指针数组的正确初始化方法

你的代码报错是因为错误地重新声明了一个大小为'+'(ASCII码值为43)的_calcul数组,这和类中声明的大小为128的静态数组冲突了。要给指定索引的元素赋值,得先正确定义整个数组,再进行赋值操作,或者用C++11的指定初始化器直接初始化目标位置。

方案1:先定义数组,再单独赋值

首先在实现文件中完整定义静态数组,默认初始化所有元素为nullptr,然后通过函数初始化目标索引的元素:

// 定义静态数组,默认初始化所有元素
test::calcul test::_calcul[128] = {};

// 初始化函数指针数组的元素
void init_calcul_map() {
    test::_calcul['+'] = test::add;
    test::_calcul['-'] = test::substract;
    test::_calcul['*'] = test::multiply;
    test::_calcul['/'] = test::divide;
}

之后在main函数开头调用初始化函数:

int main(void) {
    init_calcul_map();
    test d;
    // 测试调用:比如计算2+3
    std::cout << test::_calcul['+'](2, 3) << std::endl;
}

方案2:用C++11指定初始化器直接初始化

如果你的编译器支持C++11或更高版本,可以直接在数组定义时指定特定索引的初始值,其余元素会自动初始化为nullptr:

test::calcul test::_calcul[128] = {
    ['+'] = test::add,
    ['-'] = test::substract,
    ['*'] = test::multiply,
    ['/'] = test::divide
};

这种方式更简洁,不需要额外的初始化函数。

修改后的完整代码(方案2)

#include <cstdlib>
#include <iostream>

class test
{
public:
    test(){};
    ~test(){};
    typedef int(*calcul)(int a,int b);
    static int add(int a, int b);
    static int divide(int a, int b);
    static int multiply(int a, int b);
    static int substract(int a, int b);
    static calcul _calcul[128];
private:
    /* data */
};

int test::add(int a, int b){return a + b;};
int test::substract(int a, int b){return a - b;};
int test::multiply(int a, int b){return a * b;};
int test::divide(int a, int b)
{
    if (b == 0)
    {
        std::cerr << "Error: Division by zero\n";
        exit(1);
    }
    return a / b;
};

// 使用C++11指定初始化器初始化静态数组
test::calcul test::_calcul[128] = {
    ['+'] = test::add,
    ['-'] = test::substract,
    ['*'] = test::multiply,
    ['/'] = test::divide
};

int main(void)
{
    test d;
    std::cout << "5 + 7 = " << test::_calcul['+'](5,7) << std::endl;
    std::cout << "10 - 4 = " << test::_calcul['-'](10,4) << std::endl;
    std::cout << "6 * 8 = " << test::_calcul['*'](6,8) << std::endl;
    std::cout << "12 / 3 = " << test::_calcul['/'](12,3) << std::endl;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:42:28