繁体   English   中英

在类 C++ 中访问函数指针数组的条目

[英]Accessing entry of Array of function pointers, within a class C++

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

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

这是我的代码:

#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

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

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

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

尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM