简体   繁体   English

循环依赖c ++

[英]Circular Dependency c++

I have the following header files within my code. 我的代码中有以下头文件。 I know that the problem is that a circular dependency is occurring but I can't seem to solve it. 我知道问题是循环依赖正在发生,但我似乎无法解决它。 Any help to fix it? 有任何帮助来解决它吗?

project.h gets me this ERROR: field 'location' has incomplete type 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 gets me this ERROR field "'myDepartment' has incomplete type" 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 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

You have cyclical #include s. 你有周期性的#include s。

Try removing #include "employee.h" and #include "project.h" from department.h . 尝试从department.h删除#include "employee.h"#include "project.h"

Or vice versa. 或相反亦然。

You have an include tree like this which will cause you problems: 你有一个像这样的包含树会导致你的问题:

project.h
  department.h

employee.h
  department.h

department.h
  employee.h
  project.h

normally it is better to make your headers as independent of other class headers as possible, to do this keep your forward declarations but remove the includes, then in the .cpp file include the headers. 通常最好使您的标题尽可能独立于其他类标题,为此保留您的前向声明但删除包含,然后在.cpp文件中包含标题。

eg 例如

class project;
class employee;

class department {
  ...
  employee* headOfDepartment;
  vector<project*> myprojects;

then in department.cpp 然后在department.cpp

include employee.h and project.h and instantiate the members in your constructor, to make it even better use unique_ptr so you don't need to bother about deleting them: 包括employee.h和project.h并在构造函数中实例化成员,以便更好地使用unique_ptr,这样您就不必费心删除它们了:

class department {
  ...
  std::unique_ptr<employee> headOfDepartment;
  std::vector<std::unique_ptr<project>> myprojects;

another tip is to not have using namespace std in the header, instead include the namespace eg std::vector<...> 另一个提示是在头文件中没有using namespace std ,而是包含命名空间,例如std::vector<...>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM