我有以下代码片段
class base
{
public:
virtual void MyMethod()
{
std::cout << "Base MyMethod" << "\n";
}
};
class der : public base
{
public:
virtual void MyMethod()
{
std::cout << "Derived MyMethod" << "\n";
}
};
void foo(base* b)
{
der* d = static_cast<der*>(b);
d->MyMethod();
}
int main()
{
base* b = new der();
foo(b);
}
现在我的问题是为什么 static_Cast 在这里工作。我读到 static_casts 不能通过多态类型进行转换。那么为什么上面的例子有效 - 我在这里遗漏了什么吗?我期待动态转换只能解决这样的问题,因为它们应该与多态类型一起使用?谁能举例说明静态转换会失败而动态转换会通过?
最佳答案
“Now my question is why is
static_cast
working here.”
没有理由不工作。类型通过类派生相关,编译器知道这一点。本质上,static_cast
仅限于执行或撤消任何隐式转换,并且您确实有从 der*
到 base*
的隐式转换。
“I read that
static_cast
s cannot cast through polymorphic types.”
那只是胡说八道。
“[snip] Could anyone give an example where
static cast
would fail anddynamic cast
would pass?”
struct A { virtual ~A(){} };
struct B { virtual ~B(){} };
struct T: A, B {};
auto main()
-> int
{
T o;
A& oA = o;
//B& oB = static_cast<B&>( oA ); //! This won't compile, unrelated types.
B& oB = dynamic_cast<B&>( oA );
}
关于c++ - static_cast - 为什么它在这里工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22821860/