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

类内结构体成员函数指针调用报错,C++14环境下如何解决?

C++14中成员函数指针调用错误的解决办法

问题描述

在类中定义了包含命令与成员函数指针映射的结构体,调用结构体中的成员函数指针时,编译器报错:
called object type 'void (Atom::*)(char *, unsigned int, void *)' is not a function or function pointer

示例代码(原代码存在小问题,已标注):

class Atom
{
  public:

    struct cmds_t
    {
        char cmd[20];
        void (Atom::* func)(char * data, unsigned int length, void * _atom);
    };

    void call_ptr_func(int i, char * data, unsigned int length, void * _atom);

  private:
    cmds_t atom_cmds[16] = {NULL};  // 初始化方式有误,NULL是指针类型,不能直接初始化结构体
}; // 原代码缺少分号

// 原代码类名小写,应为Atom::
void Atom::call_ptr_func(int i, char * data, unsigned int length, void * _atom) 
{   
    // 错误的调用方式
    (this->atom_cmds[i].func)(data, length, NULL); 
}

void Atom::initialise_cmds()
{
  atom_cmds[0] = {.cmd = "!^",  .func = &Atom::funcA};
  atom_cmds[1] = {.cmd = "!TA", .func = &Atom::funcB};
  // 省略其他初始化
  atom_cmds[15] = {.cmd = "!S", .func = NULL};
}

void  Atom::funcA(char *data, unsigned int bytes, void * _atom)
{
  // 函数实现
}

错误原因

非静态成员函数指针的调用必须绑定类的实例,当前写法没有正确将成员函数指针与this实例绑定,编译器无法识别这是一个可调用的函数。

修正方法

C++14中调用成员函数指针需要使用.*或->*运算符,结合类实例来调用。修正后的call_ptr_func代码如下:

void Atom::call_ptr_func(int i, char * data, unsigned int length, void * _atom) 
{   
    // 先判断指针是否为空,避免空指针调用
    if (atom_cmds[i].func != nullptr) {
        // 使用->*运算符绑定this实例并调用
        (this->*(atom_cmds[i].func))(data, length, NULL);
    }
}

同时需要修正另外3个小问题:

  1. 类定义末尾必须添加分号:class Atom { ... };
  2. 结构体数组的初始化改为空初始化(避免类型不匹配):cmds_t atom_cmds[16] = {};
  3. 成员函数定义时类名要与类声明一致:void Atom::call_ptr_func(原代码写的atom::)

补充说明

非静态成员函数隐含一个this参数,因此成员函数指针必须明确指定调用该函数的实例。使用(this->*func_ptr)(参数)的形式,才能让编译器正确解析并调用成员函数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:35:26