我正在关注这本书 - C++ Primer来学习C ++。我正在介绍类的中间部分,并且我一直在解决头文件包括两个类的例子。
以下是两个类和头文件:
#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
#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;
}
#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
#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)
我不知道这里发生了什么。我在网上搜索了一些资源,找到了this link。它在这里没有帮助。有人可以花些时间查看并提出解决方案吗?
答案 0 :(得分:1)
很简单:
你的程序#includes“ScreenCls.h”又包含“WindowManager.h”。但是“WindowManager.h”中的“ScreenCls.h”的#include什么也没做,因为它已经包含在内,现在WindowManager.h不知道ScreenCls是什么。
你需要一个前向声明,这意味着你要么根据需要声明你的类,要么使用指针。