![](/img/trans.png)
[英]How to access static class variable in static member function of same class?
[英]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.