gpt4 book ai didi

c++ - 动态转换返回 null

转载 作者:行者123 更新时间:2023-11-28 04:46:12 25 4
gpt4 key购买 nike

我遇到了 dynamic_cast 返回 null 的问题。我正在尝试从 Card* 向下转换为 GCard*,其中 GCard 是 Card 的派生类(它是多态的)。

下面是失败的代码示例。如果有人能告诉我失败的原因,我将不胜感激。

class Card
{
public:
Card(Rank, Suit);
virtual ~Card();
void SetSelected(bool selected);

Suit mSuit;
Rank mRank;
bool mSelected;
};

class GCard : public Card
{
public:
GCard(Rank, Suit);
virtual ~GCard();

void LoadTexture();
void SetDepth(int);

sf::Sprite mSprite;
int mDepth;
private:
sf::Texture mTexture;
};

int main(void)
{
Card c(Two, clubs);
Card* pC = &c;

GCard* pG = dynamic_cast<GCard *>(pC);
if (!pG)
{
cout << "Dynamic cast returned null"; // This line is being executed
}
return 0;
}

最佳答案

dynamic_cast 正在返回 nullptr 因为您的对象很明显不是 GCard。动态转换并不是将对象转换成它们不是的事物的神秘魔法机制。它所做的只是允许您使用一个对象作为子类类型,如果它已经是该类型。

以下将按您的预期运行:

int main(void)
{
GCard c(Two, clubs); //Note the key change, the object **IS-A** GCard
Card* pC = &c;

GCard* pG = dynamic_cast<GCard *>(pC);
if (!pG)
{
cout << "Dynamic cast returned null"; // This line would no longer be executed
}
return 0;
}

关于c++ - 动态转换返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49215728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com