繁体   English   中英

如何从C ++中的静态函数内部将指向静态函数的指针作为另一个静态函数的参数传递

[英]How to pass a pointer to a static function as argument to another static function from inside a static function in C++

如何将一个静态函数的指针作为一个静态函数内部的另一个静态函数的参数传递,它们都在同一个类中? 我正在使用VisualStudio2010。我的代码大致如下所示:

//SomeClass.h
class SomeClass
{
    public:
        static AnotherClass* doSomething(AnotherClass*, AnotherClass*);
        static AnotherClass* doSomethingElse(AnotherClass*, AnotherClass*);

    private:
        typedef float (SomeClass::*SomeOperation)(float, float);
        static AnotherClass* apply(AnotherClass*, 
                                   AnotherClass*, 
                                   SomeOperation);

        static float SomeClass::operationA(float, float);
        static float SomeClass::operationB(float, float);
};

//SomeClass.cpp
AnotherClass* SomeClass::doSomething(AnotherClass* a, AnotherClass* b)
{
    return apply(a, b, &SomeClass::operationA);
}

AnotherClass* SomeClass::doSomethingElse(AnotherClass* a, AnotherClass* b)
{
    return apply(a, b, &SomeClass::operationB);
}

AnotherClass* apply(AnotherClass* a, 
                    AnotherClass* b, 
                    SomeOperation op)
{
    /* Some sanity checking and a lot of loop stuff which is the same
     * for all operations a, b, c ... */

}

我尝试了不同的变体,但不断出现编译器错误,例如:

C2664“ SomeClass :: apply”:无法从'SomeClass :: SomeOperation'中的'float(__cdecl *)(float,float)'转换参数3。

有谁知道我在做什么错以及如何解决这个问题?

静态成员函数仅仅是一个函数; 您不使用指向成员语法的指针。

所以代替

typedef float (SomeClass::*SomeOperation)(float, float);

你要

typedef float (*SomeOperation)(float, float);

您可以只传递operationA而不是&SomeClass::operationA

更改此:

private:
    typedef float (SomeClass::*SomeOperation)(float, float);

对此:

public:
    typedef float (*SomeOperation)(float, float);

或者您可以在类外声明typedef float (*SomeOperation)(float, float) ...

从typedef中删除SomeClass::

该示例中存在多种语法错误,但是在修复并完成之后,我可以编译您的代码。

暂无
暂无

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

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