2017-08-28 66 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

回答

相关问题