简体   繁体   中英

Function Pointer in c++

I am trying to use a function pointer and I am getting this error:

cannot convert from void (__thiscall MyClass::*)(void) to void (__cdecl *)(void)

// Header file - MyClass.h
class MyClass
{
public:
    MyClass();
    void funcTest();
protected:
    void (*x)();
};


// Source file 
#include "stdafx.h"
#include "MyClass.h"

MyClass::MyClass()
{
    x = funcTest;
}

void MyClass::funcTest()
{

}

(Using: Visual Studio 6)

Can anyone notice anything that I've missed?

The type of non-static member-function is not void (*)() . It is void (MyClass::*)() , which means you need to declare x as:

void (MyClass::*x)();

x = &MyClass::funcTest; //use fully qualified name, must use & also

You are trying to assign a member function pointer to a standalone function pointer. You can't use the two interchangeably, because member functions always implicitly have the this pointer as their first parameter.

void (*x)();

declares a pointer to a standalone function, while funcTest() is a member function of MyClass .

You need to declare a member function pointer like this:

void (MyClass::*x)();

For more details see the C++ FAQ .

it's because a member function is different from a normal function, and hence the function pointers are different. Hence you need to tell the compiler that you want a MyClass function pointer, not a normal function pointer.youneed to declare x as: void (MyClass::*x)();

You declare a pointer to a function not taking any arguments and returning void. But you try to assign a member function pointer to it. You will need to the declare a pointer to a member function pointer and take its address like this: &MyClass::funcTest The type of this pointer is void (MyClass::*)() Have a look at the function pointer tutorials

Yes your type definition for x is wrong. You need to defined it as a member function pointer as suggested by the compiler, ie, void(MyClass::*x)() .

http://www.parashift.com/c++-faq-lite/pointers-to-members.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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