绑定成员函数的地址

3

我有以下成员函数:

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是全局常量int,ComputeIntLenFunc和PostStepFunc是如下所示的typedef:

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' "

当我在InitFunctions()中将FunctionNames替换为GClass :: FunctionNames时,我得到了"无法将 'void (GClass ::*)(Int_t,Int_t *,Double_t *)'转换为'void (*)(Int_t,Int_t *,Double_t *)'的分配" 请帮助我。这是C ++的哪个主题?

1
OT: GClass是一个有趣的类名。如果你读你的代码,例如GClass something;,这是否意味着something _是_一个类?也许GObject会稍微好一点(尽管仍然非常通用)。 - Andre
2个回答

2

非静态成员函数指针不同于自由函数指针。你正在使用的基本上是自由函数指针类型,但这是行不通的,因为&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*);

我省略了参数名称,因为在typedef中不需要它们。

此外,在获取成员函数地址时,您必须使用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’。

1

你需要在typedef之前加上类名:

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_tInt_t*等参数,而在你的版本中它只是指向具有相同参数的自由函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接