2017-08-28 65 views
-6

我搜索通過其字符串名稱調用方法的方法。通過字符串調用方法並傳遞參數

#include <iostream> 
#include <string> 

class myClass{ 
    public: 
     void method1(int run){ 
      std::cout << run << std::endl; 
     } 
     void method2(int run){ 
      std::cout << run << std::endl; 
     } 
}; 

int main(){ 
    myClass mc; 
    std::string call; 

    call = "method1"; 
    mc.call(1); 

    call = "method2"; 
    mc.call(2); 
} 

但結果,是

「類MYCLASS」沒有名爲構件「呼叫」

我需要響應 「1」 和 「2」;

編輯::非常感謝您的幫助,我得到了下一個解決方案(我不知道對所有情況都有好處);

#include <iostream> 
#include <string> 

class myClass{ 
public: 
    void method1(int run){ 
     std::cout << "Loaded method => " << run << std::endl; 
    } 
    void method2(int run){ 
     std::cout << "Loaded method => " << run << std::endl; 
    } 
    void _loadMethods(int method, int params){ 
     switch(method) { 
      case 1: 
       method1(params); 
       break; 
      case 2: 
       method2(params); 
      break; 
      default: 
       break; 
     } 
    } 
}; 

int main(){ 
    myClass mc; 
    std::string method; 

    method = "method2"; 

    if(method == "method1"){ 
     mc._loadMethods(1, 1); 
    } 
    if(method == "method2"){ 
     mc._loadMethods(2, 2); 
    } 
} 

感謝的

+0

嘗試使用宏 – CinCout

+2

C!= C++。適當標記。 – tambre

+3

我必須避開它:C和C++是不同的語言。現在,爲了回答你的問題,C++不支持反射。考慮使用函數的名稱作爲鍵和函數指針創建一個映射,值爲 – Vanna

回答

相關問題