如何在不传递类实例的情况下从静态成员函数调用非静态成员函数 [英] How to call a non static member function from a static member function without passing class instance

查看:35
本文介绍了如何在不传递类实例的情况下从静态成员函数调用非静态成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从同一个类的静态成员函数调用一个非静态成员函数.静态函数是一个回调.它只能接收 void 作为数据,尽管我传递了一个 char*.所以我不能直接向回调提供类实例.我可以将结构而不是 char 传递给回调函数.任何人都可以提供例如代码以在静态成员函数中使用非静态成员函数.并使用静态成员函数中的结构体来使用类的实例调用非静态成员函数?

I need to call a non static member function from a static member function of the same class. The static function is a callback. It can receive only void as data, though which i pass a char*. So i cannot directly provide the class instance to the callback. I can pass a structure instead of char to the callback function. Can anyone give eg code to use the non static member function in a static member function . and use the structure in the static member function to use the instance of the class to call the non static member function?

推荐答案

通常这样的回调看起来像这样:

Normally such a callback would look like this:

void Callback( void* data)
{
    CMyClass *myClassInstance = static_cast<CMyClass *>(data);
    myClassInstance->MyInstanceMethod();
}

当然,您需要确保数据指向您的类的实例.例如

Of course, you need to make sure, data points to an instance of your class. E.g.

CMyClass* data = new CMyClass();
FunctionCallingMyCallback( data, &Callback);
delete data;

现在,如果我理解正确的话,您还需要传递一个字符*.您可以将两者都包装在一个结构中并在回调中将其解包,如下所示:

Now, if I understand you correctly, you need to also pass a char*. You can either wrap both in a struct and unwrap it in the callback like so:

MyStruct* data = new MyStruct();
data->PtrToMyClass = new CMyClass();
data->MyCharPtr = "test";
FunctionCallingMyCallback( data, &Callback);
delete data->PtrToMyClass;
delete data;


void Callback( void* data)
{
    MyStruct *myStructInstance = static_cast<MyStruct *>(data);
    CMyClass *myClassInstance = myStructInstance->PtrToMyClass;
    char * myData = myStructInstance->MyCharPtr;
    myClassInstance->MyInstanceMethod(myData);
}

或者,如果您可以修改 CMyClass 的定义,请将所有必要的数据放入类成员中,以便您可以像第一个示例中那样使用回调.

or, if you can modify the definition of CMyClass, put all the necessary data in class members, so that you can use a callback as in the first example.

这篇关于如何在不传递类实例的情况下从静态成员函数调用非静态成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆