我想以一种不合格的方式访问Base类成员(为什么?(宏魔法)来自于类的外部。策略是在Derived类中执行该操作,并将指针到-Base转换为指针到-Derived(即使实例不是Derived)。
在我尝试的范围内,代码编译和运行都是正确的:这个是标准的还是偶然的(而UB是标准的)?coliru链接
#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;
}发布于 2019-12-14 07:22:31
cast (Derived*)(&b)将等价于具有未定义行为的static_cast<Derived*>(&b),如果&b指向的对象实际上不是Derived对象的子对象。请参阅当前[static.cast]/11标准草案(至少自C++11以来就存在等效语言)。
因此,您的程序具有未定义的行为,因为根本没有创建任何Derived对象,而且b也不是Derived对象的子对象。
请注意,static_cast没有明确声明强制转换本身具有未定义的行为,但正如上面所引用的那样,它有此行为。
发布于 2019-12-14 07:56:03
我想你的代码会运行的很好。因为它确实有"a“成员变量。
struct Derived: public Base{
int c;
int getA(){
// this scope has unqualified access to Base class members
return a;
}
int getC(){
return c;
}
};
int main(void){
Base b;
std::cerr<<((Derived*)(&b))->getC()<<std::endl;
} 上面的代码运行时会出现错误,因为变量"b“中没有"c”成员,其类型实际上是基类。函数指针调用的函数getB,它不属于任何实例变量,因此不属于元变量。
https://stackoverflow.com/questions/59333078
复制相似问题