0

単純なプログラムからメソッドを抽象化しようとしています。このメソッドは、事前に宣言された 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"、メソッドが再定義されます。この問題にどのようにアプローチすればよいですか?

4

3 に答える 3

5

ヘッダーファイルでは悪い考えなので、#include <string>ヘッダーに入れて、と参照する必要があります。実際、それも悪い考えです。stringstd::stringusing namespace std.cpp

//arrayHelper.h
#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H

#include <string>

void arrayLengthCheck(int & length, const int capacity, std::string prompt);

#endif // ARRAYHELPER_H
于 2013-02-05T00:30:15.250 に答える
2

stringヘッダーファイルで使用されていますが、シンボルが見つかりません。

に移動#include <string>し、すべてをarrayHelper.hに置き換えますstringstd::string

サイドノート:

ローカルで呼び出すusing namespace std;のは慣用的な方法でありprompt、参照渡しによって1つのコピーを削除できます。以下は、コードを少し拡張したものです。

arrayHelper.h

#ifndef ARRAYHELPER_H
#define ARRAYHELPER_H

#include <string>

void arrayLengthCheck(int & length, const int capacity, const std::string& prompt);

#endif // ARRAYHELPER_H

arrayHelper.cpp

#include <iostream>
#include "arrayHelper.h"

void arrayLengthCheck(int & length, const int capacity, const std::string& prompt)
{
   using namespace std;    

    // 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;
    }
}
于 2013-02-05T00:30:29.577 に答える
0

You need to say std::string in your header file...

于 2013-02-05T00:36:30.770 に答える