绑定成员函数的地址

Address of bound member function

本文关键字:地址 函数 成员 绑定      更新时间:2023-10-16

我有一个如下的成员函数:

void GClass::InitFunctions()
{ // Initialize arrays of pointers to functions.
ComputeIntLen[0] = &ComputeILS;
ComputeIntLen[1] = &ComputeILE;
ComputeIntLen[2] = &ComputeILI;
PostStep[0] = &PSS;
PostStep[1] = &PSE;
PostStep[2] = Ψ
gRotation = new Rotation();
}

GClass显然包含所有相关的成员-:

    void ComputeILE(Int_t, Int_t *, Double_t *);
    void ComputeILI(Int_t, Int_t *, Double_t *);
    void PSS(Int_t , Int_t *, Int_t &, Int_t*);
    void PSE(Int_t, Int_t *, Int_t &, Int_t*);
    void PSI(Int_t , Int_t *, Int_t &, Int_t*);
    ComputeIntLenFunc ComputeIntLen[gNproc];
    PostStepFunc      PostStep[gNproc];
... //other members
}

其中gNproc是一个全局const int, ComputeIntLenFunc和PostStepFunc是这样的类型定义:

typedef void (*ComputeIntLenFunc)(Int_t ntracks, Int_t *trackin, Double_t *lengths);
typedef void (*PostStepFunc)(Int_t ntracks, Int_t *trackin, Int_t &nout, Int_t* trackout);

当我编译这个时,我得到gcc给出了一个错误:"ISO c++禁止使用非限定的或带括号的非静态成员函数的地址来形成指向成员函数的指针。说' &GClass::ComputeIntLenScattering ' "

当我用GClass::FunctionNames替换InitFunctions()中的FunctionNames时,我得到"无法在赋值中将' void (GClass::*)(Int_t, Int_t*, Double_t*) '转换为' void (*)(Int_t, Int_t*, Double_t*) ' "

请帮帮我。

非静态成员函数指针不同于自由函数指针。你正在使用的基本上是自由函数指针类型,这是行不通的,因为&GClass::ComputeILS的类型与ComputeIntLenFunc不兼容。

使用

:

typedef void (GClass::*ComputeIntLenFunc)(Int_t, Int_t *, Double_t *);
typedef void (GClass::*PostStepFunc)(Int_t, Int_t *, Int_t &, Int_t*);

我省略了参数名,因为它们在类型定义中不需要。

另外,当你得到成员函数的地址时,你必须使用GClass:::

ComputeIntLen[0] = &GClass::ComputeILS;
ComputeIntLen[1] = &GClass::ComputeILE;
ComputeIntLen[2] = &GClass::ComputeILI;
PostStep[0] = &GClass::PSS;
PostStep[1] = &GClass::PSE;
PostStep[2] = &GClass::PSI;

错误信息说得很清楚:

ISO c++禁止将、非限定或带括号的非静态成员函数的地址作为指向成员函数的指针。说,GClass: ComputeIntLenScattering

您还需要在typedefs中添加类:

typedef void (GClass::*ComputeIntLenFunc)(Int_t ntracks, Int_t *trackin, Double_t *lengths);
typedef void (GClass::*PostStepFunc)(Int_t ntracks, Int_t *trackin, Int_t &nout, Int_t* trackout);

那么你的(第一个)类型将意味着:这是一个指向类GClass的成员函数的指针,它接受Int_t, Int_t*等等,而在你的版本中,它只是引用了一个具有相同参数的自由函数。