想要静态成员函数调用同一个成员变量class
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
(或其成员)传递。
- 将其转换回具体类型以访问其成员。 class 静态函数可以通过提供的实例完全访问其 class 的所有成员。
所以,你可以这样做:
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
方法是静态的,这意味着它与任何特定的给定实例无关,而是与 all 实例相关,因此考虑访问 depthimagemouse
没有指定您感兴趣的实例。
没有关于 onMouse
和您的模型的更多信息,很难告诉您该怎么做。可能 param
可用于指定静态方法将接收的 A
的实例?在这种情况下,可以使用强制转换将实例返回到方法中:A *anInstance = static_cast<A *>(param);
然后您可以使用它来播放:anInstance->depthimagemouse
(请注意我们正在谈论的 depthimagemouse
给定实例?)等
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
(或其成员)传递。 - 将其转换回具体类型以访问其成员。 class 静态函数可以通过提供的实例完全访问其 class 的所有成员。
所以,你可以这样做:
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
方法是静态的,这意味着它与任何特定的给定实例无关,而是与 all 实例相关,因此考虑访问 depthimagemouse
没有指定您感兴趣的实例。
没有关于 onMouse
和您的模型的更多信息,很难告诉您该怎么做。可能 param
可用于指定静态方法将接收的 A
的实例?在这种情况下,可以使用强制转换将实例返回到方法中:A *anInstance = static_cast<A *>(param);
然后您可以使用它来播放:anInstance->depthimagemouse
(请注意我们正在谈论的 depthimagemouse
给定实例?)等