我正在阅读第 16 章,以便开始我的 C++ 课程作业。本节介绍异常处理。我理解 try/catch 构造背后的概念,但是,书中的一个例子让我有点困惑。我希望对这是如何工作的一些解释。示例代码如下:
// Includes, header guards, and namespace std...
class IntRange
{
private:
int intput;
int lower;
int upper;
public:
// Exception class
class OutOfRange { }; // This is exactly how it appears in the text.
IntRange(int low, int high) { lower = low; upper = high; }
int GetInput()
{
cin >> input;
if (input < lower || input > upper)
throw OutOfRange(); // <-- This is my question in particular. What is this?
return input;
}
};
// End header guard.
// Program entry point.
int main()
{
IntRange range(5, 10)
int userValue;
cout << "Enter a value in the range 5 - 10: ";
try
{
userValue = range.getInput();
cout << "You entered " << userValue << endl;
}
catch (IntRange::OutOfRange) // <-- Again, what is this delcaration and how can
// this data type be defined when IntRange does not
// have a default constructor?
{
cout << "That value is out of range.\n";
}
return 0;
}
代码与教科书中的代码完全相同,除了我将一些内容放在同一行以防止问题变得很长。
如果您发现任何错误,很可能是拼写错误,但最重要的几点已经过仔细检查。