C ++分配映射不同的类

时间:2018-06-28 14:49:06

标签: c++ oop typedef stdmap

此刻我遇到以下问题:
我也想分配一个类的对象作为映射结构

我的目标是: 如果我使用括号内的ID调用地图,则该功能必须启动!

我知道以下方法无效。但我会很好,我可以给我一个想法或提示,以了解如何实现此方法...

这里是一个例子:

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

非常感谢您的支持! <3

2 个答案:

答案 0 :(得分:0)

通常从其类的实例中调用成员函数:

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

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

好消息是,可以通过使函数 static

来避免类实例
class Bar
{
public:
    static void fun() {.....};
};

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

答案 1 :(得分:0)

当前格式的代码将不起作用。

两种可用的方法:

  1. 仅将其声明为一个函数,而不是类中的成员函数。
  2. 将成员函数声明为静态函数。

第二种方法的代码如下:

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