eud*_*xos 1 c++ inheritance pointers casting downcast
我想Base从班级本身之外以不合格的方式(为什么?宏魔法)访问班级成员。策略是在Derived类中执行并将指向指针转换Base为指向指针Derived(即使实例不是a Derived)。
就我尝试而言,代码编译并正确运行:这是标准还是意外(标准是UB)?链接
#include<iostream>
struct Base{
int a=3;
};
struct Derived: public Base{
int getA(){
// this scope has unqualified access to Base class members
return a;
}
};
int main(void){
Base b;
std::cerr<<((Derived*)(&b))->getA()<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)
演员(Derived*)(&b)将等同于static_cast<Derived*>(&b)具有不确定的行为,如果该对象&b指向实际上不是的子对象Derived的对象。请参阅当前 C++ 标准草案的[static.cast]/11(至少从 C++11 开始就存在等效语言)。
因此,您的程序具有未定义的行为,因为根本没有Derived创建任何对象,b也不是对象的子Derived对象。
请注意,cppreference 页面上static_cast没有明确说明演员表本身具有未定义的行为,但正如上面引用的那样。