Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java-like code (maps, function pointers)

I need to do something similar to the following code:

#include <iostream>
#include <map>

using namespace std;

typedef char (*intfunction)() ;

char a(){
    return 'a';
}

char b(){
    return 'b';
}

int main() {

map<char, intfunction> mapita;

mapita['a'] = &a;
mapita['b'] = &b;

cout << mapita['a']()
     << mapita['b']();

return 0;

}

As a matter of fact, I don't really have to much knowledge in Java, so I'm searching for some help with this.

Is there any possible way to simulate or do the same as the code above? I was seeing some examples with interfaces and so on, but couldn't make it work the same way.

like image 254
0aps Avatar asked May 08 '26 04:05

0aps


1 Answers

Check out this code:

import java.util.HashMap;
import java.util.Map;

public class test2 {
    interface Test {
        public String method();
    }

    public static void main(final String[] arg) {
        final Map<String, Test> map = new HashMap<String, Test>();

        map.put("a", new Test() {
            @Override
            public String method() {
                return "aaa";
            }
        });
        map.put("b", new Test() {
            @Override
            public String method() {
                return "bbb";
            }
        });

        System.out.println(map.get("a").method());
        System.out.println(map.get("b").method());
    }
}
like image 198
Iłya Bursov Avatar answered May 10 '26 18:05

Iłya Bursov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!