C++ assign map different classes

烂漫一生 提交于 2019-12-11 18:37:40

问题


At the moment I having following problem:
I want to assign an object of a class too a map struct

My goal is: If I call the map with the ids inside the brackets, the function must be start!

I know the following approach doesn't work. But I would be very nice, I someone can give me an idea or a tip how I can realize this approach...

Here is an example:

#include <map>
#include <functional>
#include <iostream>

class start {
    public:
        void sayhello() {
            std::cout << "Hallo!!" << std::endl;
        }
};

class end {
    public:
        void saybye() {
            std::cout << "Bye!" << std::endl;
        }
}


typedef void (*method)(void);


int main() {

    std::map<int, std::map<int, std::map<int, method>>> myMap;
    myMap[1][5][10] = start::sayhello;
    myMap[2][1][20] = end::saybye;

    // // usage:
    myMap[1][5][10]();
    myMap[2][1][20]();
}

Thank you very much for your support! <3


回答1:


Normally a member function is called from a instance of its class:

class Bar
{
public:
    void fun() {.....};
};

//somewhere in your code
Bar b;
b.fun();

The good news is that you can avoid the class instance by making the function static

class Bar
{
public:
    static void fun() {.....};
};

//somewhere in your code
Bar::fun();



回答2:


Code in the current form will not work.

Two approaches available:

  1. Declare it simply as a function and not a member function inside a class.
  2. Declare the member function as a static function.

Code for the 2nd approach is given below:

#include <map>
#include <functional>
#include <iostream>
using namespace std;

class start {
    public:
        static void sayhello() {
            std::cout << "Hallo!!" << std::endl;
        }
};

class end {
    public:
        static void saybye() {
            std::cout << "Bye!" << std::endl;
        }
};


typedef void (*method)(void);


int main() {

    std::map<int, std::map<int, std::map<int, method>>> myMap;
    myMap[1][5][10] = start::sayhello;
    myMap[2][1][20] = end::saybye;

    // // usage:
    myMap[1][5][10]();
    myMap[2][1][20]();
    return 0;
}


来源:https://stackoverflow.com/questions/51085852/c-assign-map-different-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!