【发布时间】:2018-03-24 13:11:17
【问题描述】:
class Base { int type; };
class Derived1 : public Base { ... };
class Derived2 : public Base { ... };
class Container
{
public:
Derived1 f1;
Derived2 f2;
};
Container c;
size_t offset = (size_t) static_cast<Base*>( &reinterpret_cast<Container*>(0)->f2 );
Base* base = reinterpret_cast<Base*>( (size_t) c + offset ); // ok
Base Container::* ptr = &Container::f2; // compile error!
base = c.*ptr;
是否有任何有效的方法可以使用指向成员的指针获取指向 Base 的指针?
【问题讨论】:
-
您正在取消引用
nullptr
,因此代码具有未定义的行为。也许offsetof
是你想要的。 -
reinterpret_cast(0)
是正式的 UB。除非实现保证它没问题,否则你不应该使用它。这就是offsetof
的用途。 -
这段代码很混乱。即使你说的工作部分实际上也没有编译。
Base Container::* ptr
是一个无意义的类型名称,不可能弄清楚你的真正意思。在你询问编译器错误的代码中,你试图获取甚至没有地址的东西的地址。 -
从您的示例中,
&Container::f2
无论如何都无法访问f2
在类中是私有的 - 类的默认访问,私有。 -
我认为您需要重新考虑设计
标签: c++ pointers pointer-to-member