cpp中的类java类
我想编写一个支持多种命令类型的程序。
为了使其通用且易于扩展以后的新命令,我想为每个命令编写一个类(具有自己的处理),并使用处理函数调用基本“命令”类。
我知道在 Java 中,有一个类可以帮助完成这样的事情 - 决定“流程”它正在处理的类的类型。
cpp有类似的机制吗?如果是这样,它是什么以及如何使用它?
如果没有,我该怎么做才能轻松延长它?
多谢。
I want to write a program that supports several types of commands.
In order to make it generic and easy to extend for later new commands, i want to write a class for each command (with its own handling), and call the base 'command' class with the handler function.
I know that in Java there is the class class to help with such a thing - to decide 'on the flow' the type of the class it is dealing.
Does cpp has a similar mechanism? If so, what is it and how do i use it?
If not, what can i do in order to keep it easily extended?
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用纯虚方法实现 Command 类。
http://www .exforsys.com/tutorials/c-plus-plus/c-pure-virtual-function-and-base-class.html
You could implement a Command class with a pure virtual method.
http://www.exforsys.com/tutorials/c-plus-plus/c-pure-virtual-function-and-base-class.html
虽然您可以使用 Class 类来决定 Java 中的流程,但最好使用多态性 - 它使类无需修改即可开放扩展(SOLID 中的“O”)。
在C++中也是如此。您可以使用 RTTI,但虚拟方法允许您使用命令扩展类而不修改它。
来自 Gamma 等人的“设计模式”:
Although you can use the Class class to decide flow in Java, it's better to use polymorphism - it makes the class open for extension without requiring modification (the "O" in SOLID).
The same is true in C++. You could use RTTI, but virtual methods allow you to extend the class using the commands without modifying it.
From "Design Patterns" by Gamma et al.:
您可以使用 RTTI,但我建议您找到另一种方法。
You can use RTTI, but I suggest you find another way of doing it.