std :: exception的what()方法不是虚拟的?

1 c++ virtual exception c++11

所以在参考手册中,what()方法被描述为虚拟,但似乎并没有这样做.(我正在使用g ++和c ++ 11标志进行编译)

#include <stdio.h> //printf
#include <iostream> //cout
#include <stdexcept>// std::invalid_argument
using namespace std;

void fn(){
    throw runtime_error("wowwowo");
}

int main(){
    try {fn(); }
    catch(exception a) {cout << a.what() << endl;}
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这个输出是"std :: exception",而不是错误信息"wowwowo".但是,如果我将catch类型更改为runtime_error,它将按预期运行.我有一些代码,我想捕获可能或可能不是runtime_errors的异常,我想我可以有多个catch块,但我很好奇为什么代码行为与它一样.这是打印出错误消息的代码:

#include <stdio.h> //printf
#include <iostream> //cout
#include <stdexcept>// std::invalid_argument
using namespace std;

void fn(){
    throw runtime_error("wowwowo");
}

int main(){
    try {fn(); }
    catch(runtime_error a) {cout << a.what() << endl;}
    return 0;
} 
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 11

更改此声明:

catch(exception a) {cout << a.what() << endl;}
Run Code Online (Sandbox Code Playgroud)

对此:

catch(const exception &a) {cout << a.what() << endl;}
Run Code Online (Sandbox Code Playgroud)

您必须通过引用捕获异常才能使用多态.否则,您正在切割std::runtime_error对象,因此只std::exception保留一个对象,因此std::exception::what()将调用该对象而不是std::runtime_error::what().

至于功能本身,它确实是一个virtual功能.

class exception {
public:
    //...
    virtual const char* what() const noexcept;
};
Run Code Online (Sandbox Code Playgroud)

  • 未能通过引用捕获[切片](http://stackoverflow.com/questions/274626/what-is-object-slicing). (8认同)