[英]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.