【问题标题】:Accessing entry of Array of function pointers, within a class C++在 C++ 类中访问函数指针数组的条目
【发布时间】:2016-11-30 13:43:20
【问题描述】:

我编写了一个简单的类,它使用一个接收一个索引和两个要计算的值的方法来执行基本的算术运算。

索引指示在包含函数指针的表中要执行的操作。

这是我的代码:

#include <iostream>

using namespace std;

class TArith
{
public:

    static const int  DIV_FACTOR = 1000;

    typedef int (TArith::*TArithActionFunc)(int,int);

    struct TAction
    {
        enum Values
        {
            Add,
            Sub,
            count,
        };
    };

    int action(TAction::Values a_actionIdx, int a_A, int  a_B)
    {
        return ( this->*m_actionFcns[a_actionIdx] )(a_A,a_B);
    }

private:
    int add(int a_A, int a_B)
    {
        return a_A + a_B ; 
    }

    int sub(int a_A, int a_B)
    {
        return a_A - a_B ; 
    }

    static TArithActionFunc m_actionFcns[TAction::count];
    int m_a;
    int m_b;
};

TArith:: TArithActionFunc  TArith:: m_actionFcns[TAction::count] = {
    TArith::add,
    TArith::sub
};

void main(void)
{
    TArith arithObj;
    int a=100;
    int b=50;

    for(int i = 0 ; i <TArith::TAction::count ; ++i)
    {    
        cout<<arithObj.action( (TArith::TAction::Values)i,a,b )<<endl;
    }
    cout<<endl;
}

编译器说:

'TArith::add': function call missing argument list; use '&TArith::add' to create a pointer to member
'TArith::sub': function call missing argument list; use '&TArith::sub' to create a pointer to member

为什么我需要使用 & 符号?

【问题讨论】:

  • 您是否尝试按照编译器的建议进行操作?
  • 说真的,编译器正在在错误消息中给出答案。

标签: c++ function-pointers


【解决方案1】:
TArith:: TArithActionFunc  TArith:: m_actionFcns[TAction::count] = {
    TArith::add,
    TArith::sub,
    TArith::mul,
    TArith::div
};

指向类C 的成员函数f 的指针的正确语法是&amp;C::f。你错过了领先的&amp;

试试:

TArith:: TArithActionFunc  TArith:: m_actionFcns[TAction::count] = {
    &TArith::add,
    &TArith::sub,
    &TArith::mul,
    &TArith::div
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-03
    • 2016-04-21
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多