gpt4 book ai didi

c++ - 通过传递的指针访问静态方法内部的非静态成员

转载 作者:行者123 更新时间:2023-11-28 06:17:21 28 4
gpt4 key购买 nike

不是实际代码,而是表示:

我需要从我的一个成员函数启动一个线程,我是这样做的:

return_val = pthread_create(&myThread, NULL, myStaticMethod, (void*)(this));

i) 我将 this 作为参数传递,因为静态方法不允许访问非静态成员,而且我有非静态方法和成员可以在静态方法内部访问。 这是对的吗?或者,还有其他选择吗?

myStaticMethod(void* args)    
{
args->myPublicMethod(); //Is this legal and valid?

args->myPrivateMember; //Is this legal and valid?
}

我收到一条错误消息,提示 void* 不是指向对象类型的指针,我认为 args 将被类型转换为 myClass 类型的实例。。 p>

但是,我该怎么做呢?

最佳答案

args->myPublicMethod(); //Is this legal and valid?

没有。那既不合法也无效。但是,您可以使用:

reinterpret_cast<MyClass*>(args)->myPublicMethod();

您可以从static 成员函数访问类的private 成员函数。因此,您可以使用以下方法访问类的 private 成员:

reinterpret_cast<MyClass*>(args)->myPrivateMember;

Another SO question及其答案讨论了使用 static_castreinterpret_cast 的利弊。由于您使用 void* 作为中间类型,因此您可以使用它们中的任何一个。

关于c++ - 通过传递的指针访问静态方法内部的非静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30010393/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com