std::exception 的 what() 方法不是虚拟的?
What() method for std::exception isn't acting virtual?
所以在参考手册中,what()方法被描述为虚拟的,但它似乎并没有这样做。(我正在用c++和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,它的行为与预期一样。我有一些代码,我想捕获可能是或可能不是rununtime_errors的异常,我想我可以有多个捕获块,但我很好奇为什么代码的行为是这样的。下面是打印出错误消息的代码:
#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;
};
相关文章:
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 跨 DLL 边界访问虚拟方法是否安全/可能?
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 如何编写 operator= 用于使用虚拟方法与非平凡成员的匿名联合
- 让编译器告诉什么确切的纯虚拟方法使结构抽象?
- 使用模板而不是虚拟方法的管道模式
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 为什么调用没有正文的纯虚拟方法不会导致链接器错误?
- 出于什么目的,非虚拟方法将与C++一起使用?
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 如何重写继承的嵌套类中存在的虚拟方法
- 私有虚拟方法有什么用?
- 基类可以声明虚拟方法但不定义它吗?仍然在派生类中定义
- googletest:测试基类具有纯虚拟方法的派生类时的核心转储
- 确保模拟的 GTest 方法覆盖虚拟方法
- CPP 继承虚拟方法解析顺序
- 我是否应该在包含虚拟方法的类上使用'memcpy'?如果没有,如何替换它?
- 用c++中的纯虚拟方法抽象模板类
- 解决虚拟方法的歧义继承的两种方法
- 没有针对完全专用模板类的外联虚拟方法定义