开发者

Procedural instantiation of a class - how to?

Let's assume I have a class Object with one method which simply reports the ID number of the instance. Normally, I would hardcode the instantiation of the Object class like "Object obj_1" and the calling of the method like "obj_1.report"

My question is how do I instantiate objects procedurally, for example I want to create n number of Objects, going obj_1, obj_2 and so on till obj_n. Natural I am not asking about the actual loop but about how to instantiate the class using a variable, but taking the value of the variable instead of its name and adding it to the obj_ prefix. Perhaps with casting? Also how do I procedurally call the methods of specific instances by specifying only the ID. I think both the instantiation and the method calling will work in the same way, however as a newbie I have a hard time figuring how exactly to do it on the go instead of being hardc开发者_如何学Pythonoded.

Thanks in advance!

EDIT: I am interested in c++ syntax


The best solution I can think of is to store your objects in a Map, with your IDs ("obj_1", "obj_2", etc) being the keys that refer to those instances.

Java (since you didn't specify a language) sample code would look something like this:

Map<String, Object> objMap = new HashMap<String, Object>();
for(int i = 1; i <= 10; i++) {
    objMap.put("obj_" + 1, new Object());
}

for(int i = 1; i <= 10; i++) {
    if(objMap.containsKey("obj_" + i))
        objMap.get("obj_" + i).report();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜