gpt4 book ai didi

c++ - 为什么当我抛出派生类的对象时,基类的 catch block 会捕获异常?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:09:25 25 4
gpt4 key购买 nike

<分区>

如果我正在传递派生类的对象,那么应该调用派生类的 catch block 。但是输出显示异常被基类捕获。为什么?

#include<iostream>
using namespace std;

class Base {};
class Derived: public Base {};
int main()
{
Derived d;
// some other stuff
try {
// Some monitored code
throw d;
}
catch(Base b) {
cout<<"Caught Base Exception";
}
catch(Derived d) { //This catch block is NEVER executed
cout<<"Caught Derived Exception";
}
getchar();
return 0;
}

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