0

我正在关注这本书 - C++ Primer for learning C++。我在介绍类的章节的中间,我一直在解决头文件中包含的两个类作为示例。

这是两个类和头文件:

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;
}

窗口管理器.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

窗口管理器.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

这很简单:

您的程序#includes "ScreenCls.h" 又包含 "WindowManager.h"。但是“WindowManager.h”中“ScreenCls.h”的#include 什么都不做,因为它已经被包含在内,现在 WindowManager.h 不知道 ScreenCls 是什么。

您需要一个前向声明,这意味着您要么根据需要声明尽可能多的类,要么使用指针。

于 2013-05-14T16:02:35.703 回答