我试图了解我的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
构造函数中放置一个断点,您将看到您确实在创建对象。它只是在您创建的范围内没有名称。
您可以在许多地方执行此操作(throw
,return
以及作为函数的参数)...
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