奇怪的铸造行为
有人可以解释一下代码的输出吗?
#include <iostream>
using namespace std;
class First {
public:
int a;
First() {};
First(int a) {
this->a = a;
}
int getA() {
return a;
}
virtual int getB() {
cout << "getB() from super class..." << endl;
return 0;
}
};
class Second : public First {
public:
int b;
Second(int b) {
this->b = b;
}
int getB() {
cout << "getB() from child class..." << endl;
return b;
}
};
int main() {
First* t = new Second(2);
First* cTest = dynamic_cast<First*>(t);
cout << cTest->getB() << endl;
}
我预计超类的方法将被调用,因为转换为 First。
提前致谢
问候塞巴斯蒂安
could somebody explain the output of the code.
#include <iostream>
using namespace std;
class First {
public:
int a;
First() {};
First(int a) {
this->a = a;
}
int getA() {
return a;
}
virtual int getB() {
cout << "getB() from super class..." << endl;
return 0;
}
};
class Second : public First {
public:
int b;
Second(int b) {
this->b = b;
}
int getB() {
cout << "getB() from child class..." << endl;
return b;
}
};
int main() {
First* t = new Second(2);
First* cTest = dynamic_cast<First*>(t);
cout << cTest->getB() << endl;
}
I expected the method of the super class would be called because of the casting to First.
thanks in advance
regards sebastian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
函数
getB()
在基类中是虚拟
,因此无论您是指向基类的指针还是指向派生的指针,您都会获得派生的实现。(这就是多态性的全部目的。)
The function
getB()
isvirtual
in the base class, so you get the derived implementation no matter whether you have a pointer-to-base or pointer-to-derived.(That's the whole purpose of polymorphism.)
动态向上转换层次结构不会改变您仍然指向 B 的基本事实。特别是,它不会更改用于查找将要使用的 getB() 实现的 vtable。
通常,您只需要dynamic_cast()来沿着继承层次结构向下移动,而不是向上。
A dynamic cast up the hierarchy doesn't change the fundamental fact that you're still pointing at a B. In particular, it doesn't change the vtable used to find the implementation of getB() that will be used.
Typically, you only need dynamic_cast() to go down an inheritance hierarchy, not up.
仅存在一个对象,且其类型为 Second。
为了获得您正在寻找的行为,您必须创建一个副本并将其切片:
There only exists one object, and that is of type Second.
To get the behaviour you are looking for, you are going to have to create a copy and slice it:
你不会改变你的演员阵容。您正在将 First* 转换为 First*,这只是一个赋值。由于 t 是带有
= new Second(2)
的 Second,因此您已使用子项的条目覆盖了虚拟表,因此它将调用子项的方法而不是父项的方法。cTest 只是一个指向 First 的指针,它指向与 t 完全相同的对象,因为 cTest 和 t 包含相同的内存地址,其中存在 Second 对象,这就是调用 Second 的方法的原因。
You aren't changing anything with your cast. You are casting a First* to a First*, which is simply an assignment. Since t is a Second with
= new Second(2)
, you have overridden the virtual table with the child's entries, so it will call the child's methods rather than the parents.cTest is simply a pointer-to-First which points to the exact same object that t does, because cTest and t contain the same memory address, at which exists a Second object, which is why the Second's method is called.