C ++编程方式:可以做吗? [英] C++ casting programmatically : can it be done?

查看:115
本文介绍了C ++编程方式:可以做吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个基础类别和多个派生类别。有没有办法把一个对象转换到其中一个派生类,而不需要这样写:

Let's say I have a Base class and several Derived classes. Is there any way to cast an object to one of the derived classes without the need to write something like this :


string typename = typeid(*object).name();
if(typename == "Derived1") {
   Derived1 *d1 = static_cast< Derived1*>(object);
}
else if(typename == "Derived2") {
   Derived2 *d2 = static_cast < Derived2*>(object);
}
...
else {
  ...
}


推荐答案

不要。

阅读多态性。几乎每一个动态转换的情况都是难以实现的多态的一个例子。

Read up on polymorphism. Almost every "dynamic cast" situation is an example of polymorphism struggling to be implemented.

无论你在动态转换中做出什么决定都已经做了。只需将真正的工作委托给子类。

Whatever decision you're making in the dynamic cast has already been made. Just delegate the real work to the subclasses.

您省略了示例中最重要的部分。有用的多态工作。

You left out the most important part of your example. The useful, polymorphic work.

string typename = typeid(*object).name();
if(typename == "Derived1") {
   Derived1 *d1 = static_cast< Derived1*>(object);
   d1->doSomethingUseful();
}
else if(typename == "Derived2") {
   Derived2 *d2 = static_cast < Derived2*>(object);
   d2->doSomethingUseful();
}
...
else {
  ...
}

如果每个子类实现doSomethingUseful,这一切都简单得多。和多态性。

If every subclass implements doSomethingUseful, this is all much simpler. And polymorphic.

object->doSomethingUseful();

这篇关于C ++编程方式:可以做吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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