簡體   English   中英

想要一個靜態成員函數來調用同一類的成員變量

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM