假设我有一个Base类和几个Derived类.有没有办法将对象强制转换为派生类之一,而无需编写如下内容:
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 {
...
}
Run Code Online (Sandbox Code Playgroud)
S.L*_*ott 22
别.
阅读多态性.几乎每个"动态演员"情况都是难以实现的多态性的一个例子.
无论你在动态演员表中做出什么决定都已经完成了.只需将实际工作委托给子类.
你遗漏了你的例子中最重要的部分.有用的多态工作.
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 {
...
}
Run Code Online (Sandbox Code Playgroud)
如果每个子类都实现了doSomethingUseful,那么这就简单得多了.而且是多态的.
object->doSomethingUseful();
Run Code Online (Sandbox Code Playgroud)
Derived1* d1 = dynamic_cast< Derived1* >(object);
if (d1 == NULL)
{
Derived2* d2 = dynamic_cast< Derived2* >(object);
//etc
}
Run Code Online (Sandbox Code Playgroud)
我的smartpointer类型有以下方法,模拟C#'是'和'as':
template< class Y > bool is() const throw()
{return !null() && dynamic_cast< Y* >(ptr) != NULL;}
template< class Y > Y* as() const throw()
{return null() ? NULL : dynamic_cast< Y* >(ptr);}
Run Code Online (Sandbox Code Playgroud)