希望静态成员函数调用同一类的成员变量
Want a static member function to call a member variable of the same class
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
}
相关文章:
- C++交换来自同一类成员的参数值,处理多个类
- 类成员函数无法访问同一类的私有结构节点?
- 无法将指向类的成员函数的函数指针作为参数传递给同一类的另一个成员函数
- 当两个成员位于同一类中时出错"a nonstatic member reference must be relative to a specific object"
- 如何将一个类的成员函数用作另一类的友元函数
- 如何获取同一类函数中类成员的函数指针?
- 从C 中的另一类访问类成员
- 如何将两个类成员函数与同一类中的另一个函数一起添加
- 如何为同一类对象的成员函数保留单独的变量副本?
- 如何将成员函数用于同一类的不同对象
- 如何将数据从公共方法添加到同一类中的私有成员数组中?
- 为什么一个非平凡的成员需要为同一类中的匿名联合定义构造函数
- 如何访问结构和枚举成员形成一类
- 如何在类构造函数内部对同一类的成员函数启动pthread
- 将类成员函数作为参数从同一类的另一个成员函数传递
- C++:按值将对象传递给同一类的成员函数
- 如何从同一类的另一个成员函数调用函子
- 希望静态成员函数调用同一类的成员变量
- 另一类成员函数中另一类的对象
- 一行中对同一类成员的多个访问是否以某种方式进行了优化