在下面的场景中,我没有弄清楚 static_cast 和 dynamic_cast 之间的真正区别:
**///with static_cast///**
class Foo{};
class Bar: public Foo
{
public:
void func()
{
return;
}
};
int main(int argc, char** argv)
{
Foo* f = new Foo;
Bar* b = static_cast<Bar*>(f);
b->func();
return 0;
}
Output:
Successfully Build and Compiled!
**///with dynamic_cast///**
class Foo{};
class Bar: public Foo
{
public:
void func()
{
return;
}
};
int main(int argc, char** argv)
{
Foo* f = new Foo;
Bar* b = dynamic_cast<Bar*>(f);
b->func();
return 0;
}
Output:
main.cpp: In function 'int main(int, char**)': main.cpp:26:34: error: cannot dynamic_cast 'f' (of type 'class Foo*') to type 'class Bar*' (source type is not polymorphic) Bar* b = dynamic_cast(f);
如果有人能帮助我理解这一点,我将不胜感激!
最佳答案
提示在部分
(source type is not polymorphic)
这意味着,要使 dynamic_cast
工作,它需要一个多态基类,即有一个虚方法
class Foo {
public:
virtual ~Foo() {}
};
除此之外,它不会工作,因为 f
不指向 Bar
对象。 dynamic_cast
在这种情况下将返回一个 nullptr,您必须检查它
Foo* f = new Foo;
Bar* b = dynamic_cast<Bar*>(f);
if (b != nullptr)
b->func();
关于c++ - static_cast 和 dynamic_cast 在特定场景中的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48638365/