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

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

问题描述

我需要从同一类的静态成员函数调用非静态成员函数。
静态函数是一个回调。它可以只接收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;

现在,如果我正确理解你,你还需要传递一个char *。
你可以在一个结构中包装它,并在回调中解开它,如下:

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天全站免登陆