循环依赖 c++
Circular Dependency c++
我的代码中有以下头文件。我知道问题是正在发生循环依赖,但我似乎无法解决它。有什么帮助可以解决吗?
project.h 给我这个错误:字段"位置"类型不完整
#ifndef PROJECT_H_
#define PROJECT_H_
#include <string.h>
#include "department.h"
class department;
class project{
string name;
department location;
public:
//constructors
//Setters
//Getters
};
#endif
员工.h 给我这个错误字段"'我的部门'类型不完整"
#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_
#include "department.h"
#include <vector>
class department;
class project;
class employee
{
//attributes
department myDepartment;
vector < project > myProjects;
public:
//constructor
// Distructor
//Setters
//Getters
#endif
部门.h
#ifndef DEPARTMENT_H_
#define DEPARTMENT_H_
#include <string.h>
#include "employee.h"
#include "project.h"
#include <vector>
class project;
class employee;
class department{
private:
string name;
string ID;
employee headOfDepatment;
vector <project> myprojects;
public:
//constructors
//Setters
//Getters
};
#endif
你有周期性#include
s。
尝试从department.h
中删除#include "employee.h"
和#include "project.h"
。
反之亦然。
你有一个像这样的包含树,这将导致你问题:
project.h
department.h
employee.h
department.h
department.h
employee.h
project.h
通常,最好使标题独立于其他类标头尽可能,为此保持前进声明,但删除包含,然后在.cpp文件中包括标头。
例如
class project;
class employee;
class department {
...
employee* headOfDepartment;
vector<project*> myprojects;
然后在部门.cpp
包括 employee.h 和 project.h 并在构造函数中实例化成员,以使其更好地使用 unique_ptr这样你就不需要为删除它们而烦恼:
class department {
...
std::unique_ptr<employee> headOfDepartment;
std::vector<std::unique_ptr<project>> myprojects;
另一个提示是不要在标头中包含using namespace std
,而是包含命名空间,例如 std::vector<...>
相关文章:
- 如何从C++中的依赖类型中获得它所依赖的类型
- 将--whole archive链接器选项与CMake和具有其他库依赖项的库一起使用
- 将依赖名称显式标记为类型名和模板的奇怪之处
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- C++GTKMM gui循环依赖关系
- 通过ccmake在cmake中缓存依赖选项
- 当基类是依赖类型时,这是一个缺陷吗
- 从不同的附加依赖项中识别等同命名的函数
- 如何在 CMake 中对目标依赖项进行分组?
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 为什么构建目录中新构建的共享库与安装目录中的副本具有不同的依赖项集?
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 为什么内存屏障依赖于变量?
- node-gyp 的先有鸡还是先有蛋的问题:指向依赖项中的头文件
- 反转依赖于 end() 的迭代器
- GCC,CMake,预编译标头和维护依赖项
- 使用 'typename' 关键字将非类型视为依赖上下文中的类型
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 为什么依赖模板类型在部分专用化中不可推导?