gpt4 book ai didi

c++ - dynamic_cast 返回 std::bad_cast 我不知道为什么

转载 作者:行者123 更新时间:2023-11-27 22:36:40 27 4
gpt4 key购买 nike

我有一个基类和一个派生类,如果 base 是基类的对象,我有一行会给我错误 std::bad_cast 。为什么它给我那个错误?并尝试我看到 static_cast 有效,但我不知道为什么。

行是:

#include <iostream>
class Base
{
public:
virtual void g(){std::cout<<"a";};
};

class Derived: public Base
{
public:
void g(){std::cout<<"b";};
};

void fn(Base & base)
{

Derived & pb = dynamic_cast<Derived &>(base);

pb.g();

}

int main()
{
Base f1;
fn(f1);
}

最佳答案

您正在尝试将实际上是 Base&(不是 Derived&)的 Base& 转换为 Derived& 所以它当然会失败。请记住,所有 Derived 对象也是 Base 对象,但并非所有 Base 对象都是 Derived 对象。

您可能想要做的是将实际的 Derived 对象传递给函数

int main()
{
Derived f1;
fn(f1);
}

让我用一个更具体的例子来解释。

struct Rectangle
{
Rectangle(int width, int height):
width(width), height(height) {}
virtual ~Rectangle() {}
int width, height;
};
struct Square: Rectangle
{
Square(int size): Rectangle(size, size) {}
};

int main()
{
Square square(3);
Rectangle rect(1, 2);

Rectangle& ref_to_square = square;
Rectangle& ref_to_rect = rect;

// This is okay
// ref_to_square is a reference to an actual square
dynamic_cast<Square&>(ref_to_square);

// This will fail
// ref_to_rect is *not* a reference to an actual square
dynamic_cast<Square&>(ref_to_rect);
}

关于c++ - dynamic_cast 返回 std::bad_cast 我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235111/

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