我是一名 C++ 初学者,正在为我的公司做 PoC。所以我为我的基本问题道歉。
class TestOne{
private:
TestTwo* t2;
void createInstance(TestTwo* param){
t2 = param;
}
static void staticFunctionToAccessT2(){
// Now here I want to access "t2" here in the current instance of the class
// By current instance I mean "this" in non-static context
// currently there is no function to get object, but can be created
// ** we cannot call new TestOne(), because that will create a new instance
// ** of the current class and that I don't want.
}
}
在这方面的任何帮助将不胜感激。
谢谢
===更新===
这可以作为我在 QT Creator 中开发应用程序的场景,其中我有一个预定义签名的静态函数,并且想要访问 UI 元素以进行文本更改(如 TextEdit)
原文由 Jayesh 发布,翻译遵循 CC BY-SA 4.0 许可协议
即使在 Java 中,您也无法做到这一点。
static
方法只是类的所有实例的本地辅助函数,无法访问单个类状态(例如t2
)。从方法中删除
static
或将成员变量static
变量,具体取决于您要完成的工作。编辑:
如果我理解正确,您的 SDK 需要一个函数指针,它将调用它来修改您的实例的
t2
。您的 mutator 方法应该是public
和非static
。所以假设你重新定义了staticFunctionToAccessT2
像这样:如果您要调用的实例
mutateT2
on 定义为:如果您的 SDK 需要函数指针,您可以将其传入:
正如下面 Mike Seymour 所指出的,这仅在 SDK 方法参数是
std::function
时才 有效,如果其参数是原始函数指针则无效。