C++ 异常处理中的引用捕获在c++;
在c语言的异常处理中,我经历了按值捕获/引用之间的差异++ 我偶然发现了这个博客 尝试了相同的方法,但没有得到预期的输出C++ 异常处理中的引用捕获在c++;,c++,exception,try-catch,catch-block,C++,Exception,Try Catch,Catch Block,在c语言的异常处理中,我经历了按值捕获/引用之间的差异++ 我偶然发现了这个博客 尝试了相同的方法,但没有得到预期的输出 #include<iostream> using namespace std; #include <typeinfo> class Base {}; class Derived: public Base {}; int main() { try { throw Derived(); } catch(Base &b) {
#include<iostream>
using namespace std;
#include <typeinfo>
class Base {};
class Derived: public Base {};
int main()
{
try
{
throw Derived();
}
catch(Base &b)
{
cout<<typeid(b).name();
}
return 0;
}
#包括
使用名称空间std;
#包括
类基{};
派生类:公共基{};
int main()
{
尝试
{
抛出派生的();
}
catch(基本食宿)
{
基类的析构函数必须是虚拟的
输出为“导出”
#包括
#包括
使用名称空间std;
阶级基础{
公众:
虚~Base(){};
};
派生类:公共基{};
int main()
{
尝试
{
抛出派生的();
}
catch(基本食宿)
{
尝试向基添加虚拟函数问题是Base
和Derived
不是多态类型。添加一些virtual
函数(如virtual
析构函数),它应该工作得更好。
#include<iostream>
#include <typeinfo>
using namespace std;
class Base {
public:
virtual ~Base(){};
};
class Derived: public Base {};
int main()
{
try
{
throw Derived();
}
catch(Base &b)
{
cout<<typeid(b).name();
}
return 0;
}