gpt4 book ai didi

c++ - C++ Primer 中的类进入循环依赖

转载 作者:行者123 更新时间:2023-11-28 07:37:15 29 4
gpt4 key购买 nike

我正在关注这本书 - C++ Primer用于学习C++。我在介绍类的章节中间,我一直在解决包含两个类的头文件的问题。

这是两个类和头文件:

屏幕Cls.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

屏幕Cls.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)

而且我不知道这里发生了什么。我在网上搜索了一些资源,找到了this link。 .它在这里没有帮助。有人可以花点时间看看并提出解决方案吗?

最佳答案

很简单:

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

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

关于c++ - C++ Primer 中的类进入循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16547560/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com