希望静态成员函数调用同一类的成员变量

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

本文关键字:一类 成员 变量 静态成员 函数调用 希望      更新时间:2023-10-16

headerfile.h

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 );
};

cppfile.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方法是一种静态方法,这意味着它与任何特定的给定实例无关,而与 ahl 实例无关,因此考虑访问depthimagemouse而不指定您感兴趣的实例。/p>

没有有关onMouse的更多信息,您的模型很难告诉您该怎么做。可以使用param来指定静态方法将接收的A实例?在这种情况下,可以使用铸件将实例恢复到该方法中:A *anInstance = static_cast<A *>(param);您可以与之一起玩:anInstance->depthimagemouse(请参阅我们正在谈论给定实例的depthimagemouse?),等等。

使depthimagemouse成为全局变量可以实现,但需要以专用方法进行INTIAL。这是一个实现

global.h

extern cv::Mat depthimagemouse;

global.cpp

cv::Mat depthimagemouse;

HeaderFile.h

#include "global.h"
class A
{
  std::string m_winname;
public:
  A(const std::string &winname);
  void init(const cv::Mat depthimagemouse_) {depthimagemouse = depthimagemouse_};
  static void onMouse( int evt, int x, int y, int flags, void* param );
};

cppfile.cpp

A::A(const std::string &winname)
: m_winname(winname)
{
//something..
}
void A::onMouse( int event, int x, int y, int flags, void* param )
{
  //use depthimagemouse
}