【发布时间】:2011-05-27 14:52:37
【问题描述】:
谁能解释一下代码的输出。
#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 而被调用。
提前致谢
问候塞巴斯蒂安
【问题讨论】:
-
哦不,8个空格的缩进伤害了我的眼睛
-
貌似是面试题……
-
输出是:getB() from child class... 2
-
您将 First* 转换为 First*... 为什么需要演员表?
标签: c++ casting polymorphism virtual