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

标签 c++ build header-files codeblocks

我正在关注这本书 - 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/

相关文章:

c++ - 不能在 .h 文件 C++ 中使用 glGenBuffers

C++读取文件并转换数据

c++ - 排序比较函数可以是成员函数上的指针吗?

c++ - 如何在 Visual Studio 中强制输出构建错误的绝对路径

c - 制作一个简单的C头文件

c++ - undefined reference 错误 - MPI 编译

c++ - 以毫秒为单位获取自纪元以来的时间,最好使用 C++11 chrono

c++ - 与全序相比,偏序足以构建堆吗?

eclipse - 如何只为一个项目禁用自动构建?

visual-studio - 如何在Visual Studio中更改默认的生成输出目录?