簡體   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