[英]Circular Dependency c++
我的代码中有以下头文件。 我知道问题是循环依赖正在发生,但我似乎无法解决它。 有任何帮助来解决它吗?
project.h让我得到这个错误:字段'location'的类型不完整
#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
employee.h给我这个ERROR字段“'myDepartment'有不完整的类型”
#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
department.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;
然后在department.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<...>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.