C++;进入循环依赖 我正在学习这本书——学习C++。我在介绍类这一章的中间,我被困在解析头文件中,其中包含两个类作为例子
以下是两个类和头文件: ScreenCls.h: WindowManager.h: 这是我的项目结构:C++;进入循环依赖 我正在学习这本书——学习C++。我在介绍类这一章的中间,我被困在解析头文件中,其中包含两个类作为例子,c++,build,header-files,codeblocks,C++,Build,Header Files,Codeblocks,以下是两个类和头文件: ScreenCls.h: WindowManager.h: 这是我的项目结构: /src/ScreenCls.cpp /src/WindowManager.cpp /include/ScreenCls.h /include/WindowManager.h 我正在使用Code::Blocks IDE。我在编译器设置的搜索目录中添加了/src和/include文件夹。我还将项目根目录添加到搜索目录中 现在,当我尝试构建项目时,它显示以下错误: 'ScreenCls'
/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)
我不知道这里发生了什么。我在网上搜索了一些资源,找到了。这在这里没有帮助。有人能花点时间看看并提出解决方案吗?很简单:
您的程序#包括“ScreenCls.h”,而ScreenCls.h又包括“WindowManager.h”。但是“WindowManager.h”中“ScreenCls.h”的#include没有任何作用,因为它已经被包含,现在WindowManager.h不知道ScreenCls是什么
您需要一个转发声明,这意味着您要么声明尽可能多的类,要么使用指针。(两个问答中的第一个)您是否尝试过通过其文件夹调用该类?e、 g.
#include“include/WindowManager.h”
我添加了一个转发声明:类ScreenCls
在WindowManager.h
中的WindowManager
类之前。现在它在ScreenCls
中找不到WindowManager
:(嗯……好吧……我想另一份远期声明会有所帮助,但我必须承认,我也很困惑。:)啊!建筑完成了。不得不从WindowManager头中删除转发声明,而不是包含类。在.cpp文件中,必须只包含类。需要非常了解逻辑。谢谢:)啊,那可能是WindowManager.cpp的编译。这里包含了WindowManager.h,而WindowManager.h又包含了ScreenCls.h,它现在忽略了WindowManager的定义。好了,一切都好通常不应包含.cpp文件。这有时是有道理的,但“这是错误的。”是一条很好的经验法则。(老实说,我甚至想不出一个案例有什么意义。)
#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
'ScreenCls' was not declared in this scope (WindowManager.h)
'ScreenIndex' has not been declared (WindowManager.h)
'ScreenIndex' has not been declared (ScreenCls.h)