0

我正在经历c ++中异常处理中按值/引用捕获之间的区别

偶然发现了这个博客https://blog.knatten.org/2010/04/02/always-catch-exceptions-by-reference/

尝试了同样的方法,但我没有得到预期的输出。

#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; 
}  

我得到的输出是: 4Base
正如我通过引用捕获的 typeid(b).name() 必须捕获Derived吗?还是我做错了什么?

4

1 回答 1

1

基类的析构函数必须是虚拟的。

输出为“7Derived”

#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; 
}  
于 2018-10-22T07:23:12.910 回答