我有一个 Base
类和一个 Derived
类。两者都有自己的非静态数据成员,并且都必须有标准布局。所以我不能从 Base
继承 Derived
并且必须单独声明。我知道我可以在 Derived
类中定义一个 operator Base&
,这样 Base& base = derived
就可以工作了。有没有办法让 Base* pBase = pDerived
也能工作(没有显式转换)?
最佳答案
您可以使用代理对象来表示指针:
struct Base;
struct Derived;
struct Ptr
{
Ptr(void* ptr) : ptr(ptr) { }
operator Base*() { return reinterpret_cast<Base*>(ptr); }
operator Derived*() { return reinterpret_cast<Derived*>(ptr); }
private:
void* ptr;
};
struct Base
{
Ptr operator&() { return Ptr(this); }
operator Derived&() { return *reinterpret_cast<Derived*>(this); }
};
struct Derived
{
Ptr operator&() { return Ptr(this); }
operator Base&() { return *reinterpret_cast<Base*>(this); }
};
void bar(Base*)
{ }
void foo()
{
Derived derived;
Base* base1 = &derived;
Base& base2 = derived;
bar(&derived);
}
如果使用此正式解决方案,应针对 UB 进行仔 segmentation 析。
关于c++ - 如何模仿派生到基指针自动转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51808216/