[英]C++ dynamic cast with inheritance
#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,但在分配给 ab 时,您隐式地转换回 A,因此 dynamic_cast 再次丢失。
ab 所指向的对象的实际类型仍然是 B,但是访问该对象的指针是 A 类型的,因此 A::foo 被选中。 不过,如果 foo 是虚拟的,情况就会不同。
如果从 A 指针调用 foo() 函数,则会调用 A 类的 foo()。 我相信您正在寻找一种虚拟行为。 如果是这种情况,请将 A 类的 foo() 声明为:
virtual void foo() { cout << "foo in A" << endl; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.