循环依赖 c++

Circular Dependency c++

本文关键字:c++ 依赖 循环      更新时间:2023-10-16

我的代码中有以下头文件。我知道问题是正在发生循环依赖,但我似乎无法解决它。有什么帮助可以解决吗?

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<...>