#include <iostream>
using namespace std;
struct Base {
void doBase() {
cout << "bar" << endl;
}
};
struct Derived : public Base {
void doBar() {
cout << "bar" << endl;
}
};
int main()
{
Base b;
Base* b_ptr = &b;
Derived* d_ptr = static_cast<Derived*>(b_ptr);
d_ptr->doBar(); //Why there is no compile error or runtime error?
return 0;
}
该程序的输出为bar\n
。
d_ptr
实际上,它在调用派生类成员函数时指向基类。
是未定义的行为还是其他?
是的,这是未定义的行为。
因为您使用过,所以没有编译时错误static_cast
-这是一种告诉编译器“我比您更了解类型的方法”。您告诉您的对象是Derived
。您对编译器撒谎-这是未定义的行为。
碰巧是有效的,因为doBar()
不使用任何Derived
成员。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句