C++ 分配映射不同的类 [英] C++ assign map different classes

查看:81
本文介绍了C++ 分配映射不同的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的目标是:如果我用括号内的id调用地图,则该函数必须启动!

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...

这是一个例子:

#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

Thank you very much for your support! <3

推荐答案

当前表单中的代码将不起作用.

Code in the current form will not work.

有两种可用的方法:

  1. 将其简单地声明为函数而不是类中的成员函数.
  2. 将成员函数声明为静态函数.

第二种方法的代码如下:

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

这篇关于C++ 分配映射不同的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆