Mil*_*rdy 4 c++ oop inheritance dynamic-cast static-cast
我在下面的场景中没有弄清楚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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
成功构建和编译!
**///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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
main.cpp:在函数'int main(int,char**)'中:main.cpp:26:34:错误:不能用dynamic_cast'f'(类型'类Foo*')来键入'class Bar*'(源类型不是多态的)Bar*b = dynamic_cast(f);
如果有人能帮助我理解这一点,我将不胜感激!
提示是在部分
(源类型不是多态的)
这意味着,为了dynamic_cast工作,它需要一个多态基类,即具有虚方法
class Foo {
public:
virtual ~Foo() {}
};
Run Code Online (Sandbox Code Playgroud)
除此之外,它不起作用,因为f不指向一个Bar对象.dynamic_cast在这种情况下将返回nullptr,您必须检查
Foo* f = new Foo;
Bar* b = dynamic_cast<Bar*>(f);
if (b != nullptr)
b->func();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
146 次 |
| 最近记录: |