简体   繁体   English

c ++中的函数指针

[英]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) 无法从void (__thiscall MyClass::*)(void)转换为void (__thiscall MyClass::*)(void) 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) (使用:Visual Studio 6)

Can anyone notice anything that I've missed? 任何人都可以注意到我错过的任何东西吗?

The type of non-static member-function is not void (*)() . 非静态成员函数的类型不是void (*)() It is void (MyClass::*)() , which means you need to declare x as: 它是void (MyClass::*)() ,这意味着你需要将x声明为:

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. 你不能互换地使用这两个,因为成员函数总是隐式地将this指针作为它们的第一个参数。

void (*x)();

declares a pointer to a standalone function, while funcTest() is a member function of MyClass . 声明指向独立函数的指针,而funcTest()MyClass的成员函数。

You need to declare a member function pointer like this: 你需要像这样声明一个成员函数指针:

void (MyClass::*x)();

For more details see the C++ FAQ . 有关更多详细信息,请参阅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)(); 因此,您需要告诉编译器您需要MyClass函数指针,而不是普通函数指针。您需要将x声明为: void (MyClass::*x)();

You declare a pointer to a function not taking any arguments and returning void. 您声明一个指向函数的指针,该函数不接受任何参数并返回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 你将需要声明一个指向成员函数指针的指针并获取它的地址,如下所示: &MyClass::funcTest这个指针的类型是void (MyClass::*)()看一下函数指针教程

Yes your type definition for x is wrong. 是的x的类型定义是错误的。 You need to defined it as a member function pointer as suggested by the compiler, ie, void(MyClass::*x)() . 您需要将其定义为编译器建议的成员函数指针,即void(MyClass::*x)()

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

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

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