簡體   English   中英

如何將方法作為參數傳遞?

[英]How to pass a method as parameter?

有這個課程:

class Automat
{
private:
    // some members ... 
public:
    Automat();
    ~Automat();
    void addQ(string& newQ) ; 
    void addCharacter(char& newChar)  ;
    void addLamda(Lamda& newLamda) ; 
    void setStartSituation(string& startQ) ; 
    void addAccQ(string& newQ) ;
    bool checkWord(string& wordToCheck) ; 
    friend istream& operator >> (istream &isInput, Automat &newAutomat);
    string& getSituation(string& startSituation) ; 
};

還有一個叫做Menu類,它有以下方法:

void Menu::handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) () )
{
    // some code ...
      (*autoToHandle).*methodToDo() ; 
}

(*autoToHandle).*methodToDo() ; 給出錯誤。

正如您所看到的,我嘗試將任何方法從Automat類作為參數傳遞給handleStringSituations方法,但沒有成功。

你怎么稱呼它? C ++不是動態類型語言; 它是靜態類型的。 因此,您調用的所有內容都必須具有一組特定的參數,並且必須鍵入每個參數。 沒有辦法用一些參數調用“某個函數”,並希望它可以在運行時進行整理。

您需要一個特定的界面。 methodToDo需要有某種界面; 沒有一個,你不能稱之為。

您可以做的最好的事情是擁有多個版本的handleStringSituations ,其中每個版本都采用不同的成員指針類型:

void handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) ()) ;
void handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) (string&)) ;
void handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) (Lamda&)) ;

你嘗試做的通常被稱為閉包,這是一個強大的功能編程概念。 我建議你研究Boost :: Phoenix,而不是重新發明輪子,它提供了一個很好的,經過同行評審的庫。

http://www.boost.org/doc/libs/1_47_0/libs/phoenix/doc/html/index.html

但是,由於C ++是一種靜態類型語言,因此您必須進行一些編組操作。 在C ++中沒有像泛型函數(對象)這樣的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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