【发布时间】:2016-11-11 18:57:39
【问题描述】:
#include <iostream>
using namespace std;
class A
{
public:
void foo() { cout << "foo in A" << endl; }
};
class B : public A
{
public:
void foo() { cout << "foo in B" << endl; }
};
int main() {
A* a = new B;
a->foo(); // will print "foo in A" because foo is not virtual
B* b = new B;
b->foo(); // will print "foo in B" because static type of b is B
// the problem
A* ab;
ab = dynamic_cast<B*>(new B);
ab->foo(); // will print "foo in A" !!!!!
}
'dynamic_cast' 不会改变 ab 的静态类型吗?我的意思是,从逻辑上讲,它接缝相当于 B* ab = new B;因为铸造..但事实并非如此。
我认为动态转换会改变对象的静态类型,我错了吗?如果是这样,有什么区别:
A* ab = dynamic_cast<B*>(new B);
和
A* ab = new B;
谢谢
【问题讨论】:
-
想想
dynamic_cast<B*>被应用于什么。new B的类型是什么?
标签: c++ inheritance casting dynamic-cast