C++ assign map different classes

2019-08-27 22:04发布

问题:

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