我们可以从
static_cast
到Base*
Derived*
,但在我的例子中,当演员应该发生时,这种关系是不可见的。有什么技巧(当然除了reinterpret_cast
)可以让它发挥作用吗?
struct Derived;
struct Base
{
Base()
{
//Is there a way to make it work?
//Derived* d = static_cast<Derived*>(this);
}
};
struct Derived: public Base
{
};
int main()
{
Base b{};
// Here it works as the compiler is aware of the relationship
Derived* d = static_cast<Derived*>(&b);
}
您可以在这里尝试一下。
要回答您的问题 - 您需要将Base()
的
实现移到
Derived
的声明之后,例如:
struct Derived;
struct Base
{
Base();
};
struct Derived: public Base
{
};
Base::Base()
{
// Here it works as the compiler is aware of the relationship
Derived* d = static_cast<Derived*>(this);
}
int main()
{
Base b{};
// Here it works as the compiler is aware of the relationship
Derived* d = static_cast<Derived*>(&b);
}
话虽这么说,你所做的事情是有风险的,因为
this
构造函数内的 Base
和 b
内的 main()
都没有指向有效的 Derived
对象。 如果您尝试取消引用强制转换的指针,您将调用未定义的行为。