从静态函数调用非静态变量

新手上路,请多包涵

我是一名 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 许可协议

阅读 393
1 个回答

即使在 Java 中,您也无法做到这一点。

static 方法只是类的所有实例的本地辅助函数,无法访问单个类状态(例如 t2 )。

从方法中删除 static 或将成员变量 static 变量,具体取决于您要完成的工作。

编辑:

如果我理解正确,您的 SDK 需要一个函数指针,它将调用它来修改您的实例的 t2 。您的 mutator 方法应该是 public 和非 static 。所以假设你重新定义了 staticFunctionToAccessT2 像这样:

 public: void mutateT2();

如果您要调用的实例 mutateT2 on 定义为:

 TestOne foo;

如果您的 SDK 需要函数指针,您可以将其传入:

 std::bind(&TestOne::mutateT2, foo)

正如下面 Mike Seymour 所指出的,这仅在 SDK 方法参数是 std::function 时才 有效,如果其参数是原始函数指针则无效。

原文由 Jonathan Mee 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题