単純なプログラムからメソッドを抽象化しようとしています。このメソッドは、事前に宣言された CAPACITY 定数に対して配列の長さをテストし、条件が満たされない場合はエラー メッセージを吐き出します。ただし、メソッドを保持する .cpp ファイルを使用してヘッダー ファイルを作成するのに問題があります。
ヘッダファイル:
//arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H
void arrayLengthCheck(int & length, const int capacity, string prompt);
#endif // ARRAYHELPER_H
コードファイル:
//arrayHelper.cpp
#include <iostream>
#include <string>
#include "arrayHelper.h"
using namespace std;
void arrayLengthCheck(int & length, const int capacity, string prompt)
{
// If given length for array is larger than specified capacity...
while (length > capacity)
{
// ...clear the input buffer of errors...
cin.clear();
// ...ignore all inputs in the buffer up to the next newline char...
cin.ignore(INT_MAX, '\n');
// ...display helpful error message and accept a new set of inputs
cout << "List length must be less than " << capacity << ".\n" << prompt;
cin >> length;
}
}
#include "arrayHelper.h"
エラーを含むこの main.cpp ファイルを実行するstring is not declared
と、ヘッダー ファイルに出力されます。ヘッダー ファイルに文字列を含めても効果はありませんが#include "arrayHelper.cpp"
、メソッドが再定義されます。この問題にどのようにアプローチすればよいですか?