C ++クラスの割り当てを開始するために、第16章を読んでいます。このセクションでは、例外処理について説明します。try / catch構造の背後にある概念は理解していますが、この本の例の1つは少し混乱しています。これがどのように機能しているかについての説明を期待しています。サンプルコードは次のとおりです。
// 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;
}
コードは教科書に記載されているとおりですが、質問が長くならないようにするために同じ行にいくつかのものを配置している点が異なります。
エラーに気付いた場合は、タイプミスである可能性が高いですが、最も重要な点が再確認されています。