0

私は本に従っています - C++を学ぶためのC++入門。私はクラスを紹介する章の途中で、そこで例として取り上げられた 2 つのクラスのヘッダー ファイル インクルードを解決することに行き詰まっています。

2 つのクラスとヘッダー ファイルを次に示します。

ScreenCls.h:

#ifndef SCREENCLS_H
#define SCREENCLS_H

#include <iostream>

#include "WindowManager.h"

using namespace std;

class ScreenCls {
    friend void WindowManager::clear(ScreenIndex);

public:
    typedef string::size_type pos;
    ScreenCls() { }
    ScreenCls(pos height, pos width, char c): height(height), width(width), contents(height * width, c) { }

    ScreenCls &set(char);
    ScreenCls &set(pos, pos, char);

    char get() const { return contents[cursor]; }  // Implicitly inline

private:
    pos cursor;
    pos height;
    pos width;
    string contents;
};

#endif // SCREENCLS_H

ScreenCls.cpp:

#include "ScreenCls.h"

char ScreenCls::get(pos r, pos c) const {
    pos row = r * width;
    return contents[row + c];
}

ScreenCls &ScreenCls::set(char ch) {
    contents[cursor] = ch;
    return *this;
}

ScreenCls &ScreenCls::set(pos r, pos c, char ch) {
    contents[r * width + c] = ch;
    return *this;
}

WindowManager.h:

#ifndef WINDOWMANAGER_H
#define WINDOWMANAGER_H

#include <iostream>
#include <vector>
#include "ScreenCls.h"

using namespace std;

class WindowManager {

public:
    // location ID for each screen on window
    using ScreenIndex = vector<ScreenCls>::size_type;
    // reset the Screen at the given position to all blanks
    void clear(ScreenIndex);

private:
    vector<ScreenCls> screens{ Screen(24, 80, ' ') };
};

#endif // WINDOWMANAGER_H

WindowManager.cpp:

#include "WindowManager.h"
#include "ScreenCls.h"

void WindowManager::clear(ScreenIndex index) {
    ScreenCls &s = screens[i];
    s.contents = string(s.height * s.width, ' ');
}

これは私のプロジェクト構造です:

/src/ScreenCls.cpp 
/src/WindowManager.cpp 
/include/ScreenCls.h 
/include/WindowManager.h

Code::Blocks IDEを使用しています。コンパイラ設定の検索ディレクトリにフォルダを追加/srcしました。また、プロジェクトのルート ディレクトリを検索ディレクトリに追加しました。/include

今、プロジェクトをビルドしようとすると、次のエラーが表示されます。

'ScreenCls' was not declared in this scope (WindowManager.h)  
'ScreenIndex' has not been declared (WindowManager.h)  
'ScreenIndex' has not been declared (ScreenCls.h)  

そして、私はここで何が起こっているのかわかりません。オンラインでいくつかのリソースを検索したところ、このリンクが見つかりました。そして、それはここでは役に立ちません。誰かが解決策を見て提案するのに時間がかかることがありますか?

4

1 に答える 1

1

それは簡単です:

あなたのプログラムには、#include "ScreenCls.h" が含まれており、これには "WindowManager.h" が含まれています。しかし、"WindowManager.h" 内の "ScreenCls.h" の #include は、既にインクルードされており、WindowManager.h は ScreenCls が何であるかを認識していないため、何もしません。

代わりに前方宣言が必要です。つまり、クラスを必要なだけ宣言するか、ポインターを使用します。

于 2013-05-14T16:02:35.703 に答える