gpt4 book ai didi

c++ - 为什么异常中没有创建对象?

转载 作者:太空狗 更新时间:2023-10-29 21:04:09 26 4
gpt4 key购买 nike

我正在尝试了解我的 C++ 类的异常,但我对这个程序有些不了解。为什么异常中没有创建对象?为什么只提供类名和参数?

此处:throw(testing ("testing this message"));

#include <iostream>
#include <string>
#include <stdexcept>

using namespace std;


class testing: public runtime_error
{
public:
testing(const string &message)
:runtime_error(message) {}
};

int main()
{
try {
throw( testing ("testing this message"));
}
catch (runtime_error &exception) {
cerr << exception.what() << endl;
}
return 0;
}

最佳答案

您正在创建一个临时的 testing 对象。我知道语法看起来有点滑稽,因为它没有命名。您期望看到 testing myObj("Testing this message");,但您得到的是没有变量名的相同内容。

在您的testing 构造函数中放置一个断点,您会发现您确实在创建一个对象。它只是在您创建它的范围内没有名称。

您可以在很多地方执行此操作(throwreturn 以及作为函数的参数)...

return std::vector<int>(); // return an empty vector of ints

func(MyClass(1, 2, 3)); // passing `func` a `MyClass` constructed with the arguments 1, 2, and 3

关于c++ - 为什么异常中没有创建对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12031340/

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