gpt4 book ai didi

c++ - what() 调用的解释

转载 作者:太空宇宙 更新时间:2023-11-04 15:16:56 24 4
gpt4 key购买 nike

using namespace std;

struct MyException : public exception
{
const char * what () const throw () // <--- This
{
return "C++ Exception";
}
};

请考虑标记的行。有人可以向我解释该语句中使用的语法吗

我认为我应该将查询范围缩小到仅"const throw()" 部分...

谢谢大家的回复

最佳答案

这是一个成员函数定义。

  • const char * 是返回类型,指向常量字符的指针,按照惯例,它是零终止字符串数组的第一个字符。
  • 什么是函数名
  • ()是一个空参数列表,表示该函数不带参数
  • const 限定函数,因此可以在const 对象上调用,不能直接修改对象的成员
  • throw () 是一个异常规范,可以防止它抛出任何异常。

这会覆盖 exception 基类中声明的虚函数,允许您获得描述抛出的特定异常的文本消息:

try {
// Throw a specific type
throw MyException();
} catch (std::exception const & ex) {
// Catch a generic type and extract the message
std::cerr << ex.what() << '\n'; // prints "C++ Exception"
}

关于c++ - what() 调用的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30323256/

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