繁体   English   中英

想要一个静态成员函数来调用同一类的成员变量

[英]Want a static member function to call a member variable of the same class

头文件

class A
{
  cv::Mat depthimagemouse;
  std::string m_winname;

public:

  A(const std::string &winname, const cv::Mat depth_clean);
  static void onMouse( int evt, int x, int y, int flags, void* param );
};

cpp文件

A::A(const std::string &winname, const cv::Mat depth_clean)
    : m_winname(winname), depthimagemouse(depth_clean)
{
//something..
}

void A::onMouse( int event, int x, int y, int flags, void* param )
{
//Here I want to use depthimagemouse member variable (and other members..)
}

我的问题是如何在onMouse方法中使用depthimagemouse变量?

如果图书馆没有在文档中的任何地方对此进行解释,我会感到惊讶,但是无论如何。 当您使用不支持成员函数的回调时,这是标准过程,但是您仍然需要一种访问成员数据的方法。 因此,您执行以下操作:

  • 注册回调时,将对实例的引用作为用户数据指针param (或其成员)传递。
  • 将其转换回具体类型以访问其成员。 类静态函数可以通过提供的实例完全访问其类的所有成员。

因此,您可以这样操作:

auto &that = *static_cast<A *>(param); // <= C++03: use A &that
// Cast to const A if you want, or use a pointer, or etc.
std::cout << that.depthimagemouse << std::endl;

或者,从语法上来说,立即发送给成员函数并使其执行所有操作通常更好:

static_cast<A *>(param)->doRestOfStuff(evt, x, y, flags);
// Include a const in the cast if the method is const

或介于两者之间的任何位置。

depthimagemouse是实例成员,表示每个A实例(如果需要,对象)都有自己的depthimagemouse 您的onMouse方法是一个静态方法,这意味着它与任何特定的给定实例都不相关,而是与所有实例无关,因此考虑访问depthimagemouse而不指定您感兴趣的实例是没有意义的。

如果没有有关onMouse和模型的更多信息,很难告诉您该怎么做。 可以使用param来指定静态方法将接收的A实例吗? 在这种情况下,可以使用A *anInstance = static_cast<A *>(param);将实例返回到方法内部: A *anInstance = static_cast<A *>(param); 然后可以使用它播放: anInstance->depthimagemouse (看看我们在谈论给定实例的depthimagemouse吗?),等等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM