基础到派生的 static_cast,不可见的关系

问题描述 投票:0回答:1

我们可以从

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);
}

您可以在这里尝试一下

c++ c++17 static-cast
1个回答
0
投票

要回答您的问题 - 您需要将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
对象。 如果您尝试取消引用强制转换的指针,您将调用未定义的行为

© www.soinside.com 2019 - 2024. All rights reserved.