[英]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" !!!!!
}
Does the 'dynamic_cast' not change the static type of ab? 'dynamic_cast' 不会改变 ab 的静态类型吗? I mean, logically, it seams equivalent to B* ab = new B;
我的意思是,从逻辑上讲,它相当于 B* ab = new B; because of the casting.. But it does not.
因为铸造.. 但它没有。
I thought that dynamic cast changes the static type of the object, am I wrong?我以为动态转换会改变对象的静态类型,我错了吗? And if so, what is the difference between:
如果是这样,有什么区别:
A* ab = dynamic_cast<B*>(new B);
and和
A* ab = new B;
Thanks谢谢
You are dynamic_cast
ing to B, but at time of assignment to ab, you are implicitely casting back to A, so the dynamic_cast gets lost again.您正在将
dynamic_cast
为 B,但在分配给 ab 时,您隐式地转换回 A,因此 dynamic_cast 再次丢失。
The actual type of the object ab is pointing to still remains B, but the pointer the object is accessed with is of type A, so A::foo is selected. ab 所指向的对象的实际类型仍然是 B,但是访问该对象的指针是 A 类型的,因此 A::foo 被选中。 It would have been different if foo was virtual, though.
不过,如果 foo 是虚拟的,情况就会不同。
If you call the foo() function from A pointer, foo() of class A will be called.如果从 A 指针调用 foo() 函数,则会调用 A 类的 foo()。 I believe you're looking for a virtual behavior.
我相信您正在寻找一种虚拟行为。 If that is the case, declare foo() of class A as:
如果是这种情况,请将 A 类的 foo() 声明为:
virtual void foo() { cout << "foo in A" << endl; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.