如何捕获一般异常并显示其派生的内容()

use*_*456 2 c++ exception try-catch

这样的代码会出现问题:

#include <cstdlib>
#include <iostream>
#include <stdexcept>

using namespace std;

int main(int argc, char** argv) {

try {
    throw  runtime_error("Message");
} catch (exception e) {
    cout << e.what();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我希望Message能出现.但结果是std::exception.我认为virtual functions可以从超类引用中调用子类.怎么解决这个问题?

thi*_*ton 7

C++明确区分了引用和值复制.使用

catch (const std::exception& e) 
Run Code Online (Sandbox Code Playgroud)

通过引用而不是值来捕获.