考虑以下代码:
class user_error : public std::runtime_error
{
public:
using std::exception::what;
explicit user_error(const std::string& what_arg):std::runtime_error(what_arg){}
};
class with_overriden_what : public user_error {
public:
with_overriden_what(const std::string& val) : user_error("user_error"), message(val) { }
std::string message;
virtual const char* what() const noexcept {
return message.c_str();
}
};
用这个电话:
with_overriden_what ex("thrown");
std::cout << "1. direct result: " << ex.what() << "\n";
std::cout << "2. sliced result: " << static_cast<user_error>(ex).what() << "\n";
std::cout << "3. ranged result: " << ex.user_error::what() << "\n";
令我惊讶的是 2 和 3 的结果不同:
1. direct result: thrown
2. sliced result: user_error
3. ranged result: std::exception
问:标准中有一个段落可以解决这种行为吗?