简体   繁体   English

在类中分配函数指针会导致C ++中的值类型错误

[英]Assigning function pointer within a class gives value type error in C++

I've got this code within Entity.h, which is inherited by other classes. 我在Entity.h中有此代码,该代码由其他类继承。 The idea is that in the inheriting classes can change the function either to avoid inheritance or to modify behavior. 这个想法是,在继承类中,可以更改函数以避免继承或修改行为。

public:
Entity(void)
{
    updateFunction = emptyFunction;
};
~Entity(void);
protected:
    void emptyFunction(){}
void (*updateFunction)();

The problem is that I get this error on compilation: 问题是在编译时出现此错误:

Error   2   error C2440: '=' : cannot convert from 'void (__cdecl Entity::* )(void)' to 'void (__cdecl *)(void)'    c:\documents and settings\administrator\my documents\visual studio 2010\projects\projectname\[projectname]\Entity.h 16  1   [projectname]

I've looked at tutorials all over again, it's been a while since I learned these stuff, but I cannot see some dissimilarity, what could be going wrong? 自从我学习这些东西以来已经有一段时间了,但是我看不到一些不同之处,这可能是哪里出了问题? IntelliSense unrelines the '=' symbol as the point of the mistake. IntelliSense取消取消将'='符号表示为错误点。 I hope I didn't overlook anything. 我希望我不要忽视任何事情。

Thanks a lot in advance!! 在此先多谢!!

You need to decalre pointer function as: 您需要将指针函数标为:

class Entity{
public:
    Entity(void)
    {
        updateFunction = &Entity::emptyFunction;
        // ...
        (this->*updateFunction)(); //Call
    };
    ~Entity(void);
protected:
    void emptyFunction(){}
    void (Entity::*updateFunction)();
};

In fact updateFunction is not a normal function and it's a class member function. 实际上, updateFunction不是普通函数,而是类成员函数。

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

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