gpt4 book ai didi

c++ - 为什么 MinGW 4.8 不将 ex.what() 视为虚拟的?

转载 作者:行者123 更新时间:2023-11-28 06:58:42 27 4
gpt4 key购买 nike

我使用 Qt Creator 3.0.1 和 MinGW 4.8 32 位作为编译器。

当我将以下代码放入 main() 函数的最顶部时(在 Qt 执行所有操作之前),我在控制台上得到的输出是“std::exception”,不像我期望的那样“哎呀”:

try {
throw std::logic_error{"Whoops"};
}
catch (std::exception ex) {
std::cout << ex.what() << std::endl;
}

我还尝试通过指针访问 what():

try {
throw std::logic_error{"Whoops"};
}
catch (std::exception ex) {
std::exception* ex2 = &ex;
std::cout << ex2->what() << std::endl;
}

如我所料,在 VS2013 中编译的完全相同的代码输出“哎呀”。

std::exception::what() 是虚拟的,那么为什么会发生这种情况?

最佳答案

正如克里斯所说,你是 slicing the information .您可以通过捕获 const 引用(demo)来防止这种情况:

try {
throw std::logic_error{"Whoops"};
} catch (const std::exception& ex) {
std::cout << ex.what() << std::endl; // Whoops
}

关于c++ - 为什么 MinGW 4.8 不将 ex.what() 视为虚拟的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22821328/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com