小编alk*_*ion的帖子

为什么从指针到Base的static_cast到指向派生的指针"无效?"

所以我有这个代码:

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

mTree-> getNode(groupID)返回PCSNode*.节点是从PCSNode公开派生的.

我在static_cast上找到的所有文档都说明了这一点:"static_cast运算符可用于操作,例如将指向基类的指针转换为指向派生类的指针."

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

这是什么原因?当我将其切换为C风格的演员表时,编译器没有任何抱怨.

谢谢.

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

错误:语义问题:不允许从"PCSNode*"到"Node*"的Static_cast

c++ casting downcast

6
推荐指数
1
解决办法
5837
查看次数

标签 统计

c++ ×1

casting ×1

downcast ×1