[英]What() method for std::exception isn't acting virtual?
因此,在参考手册中,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;
}
此输出是“ 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;
}
更改此语句:
catch(exception a) {cout << a.what() << endl;}
对此:
catch(const exception &a) {cout << a.what() << endl;}
您必须通过引用来捕获异常,以使其使用多态性。 否则,您将对std::runtime_error
对象进行切片,以便仅保留一个std::exception
对象,因此将调用std::exception::what()
而不是std::runtime_error::what()
。
至于功能本身,它确实是一个virtual
功能。
class exception {
public:
//...
virtual const char* what() const noexcept;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.