通过字符串调用方法并传递参数

时间:2017-08-28 06:09:08

标签: c++

我搜索一种通过字符串名称调用方法的方法。

#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);
}

但结果是

  

'class Myclass'没有名为'call'的成员

我需要回复“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);
    }
}

感谢的

1 个答案:

答案 0 :(得分:0)

这在&#34; raw&#34;中是不可能的。 C ++。但是......你想要实现的是某种反射或类元类信息 您可以查看此项目:http://www.axelmenzel.de/projects/coding/rttr,使用Qt:http://doc.qt.io/qt-5/qmetatype.html#details或google进行C ++反射。

相关问题