繁体   English   中英

为什么从指向 Base 的指针到指向 Derived 的指针的 static_cast “无效”?

[英]Why is a static_cast from a Pointer to Base to a Pointer to Derived “invalid?”

所以我有这个代码:

Node* SceneGraph::getFirstNodeWithGroupID(const int groupID)
{
    return static_cast<Node*>(mTree->getNode(groupID));
}

mTree->getNode(groupID) 返回一个 PCSNode*。 Node 是从 PCSNode 公开派生的。

我在 static_cast 上找到的所有文档都说明了这一点:“static_cast 运算符可用于诸如将指向基本 class 的指针转换为指向派生 class 的指针等操作。”

然而,XCode 的 (GCC) 编译器表示从 PCSNode* 到 Node* 的 static_cast 无效且不允许。

这是什么原因? 当我将它切换到 C 风格的演员表时,编译器没有抱怨。

谢谢。

更新:即使问题已得到解答,我仍会发布编译器错误以确保完整性,以防其他人遇到同样的问题:

错误:语义问题:不允许从“PCSNode *”到“Node *”的静态转换

原因很可能是Node的定义对编译器不可见(例如,它可能只是前向声明的: class Node; )。

自包含示例:

class Base {};

class Derived; // forward declaration

Base b;

Derived * foo() {
    return static_cast<Derived*>( &b ); // error: invalid cast
}

class Derived : public Base {}; // full definition

Derived * foo2() {
    return static_cast<Derived*>( &b ); // ok
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM