1

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

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

employee.h 给我这个错误字段“'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

部门.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
4

2 回答 2

3

你有循环#include的。

尝试从. #include "employee.h"_#include "project.h"department.h

或相反亦然。

于 2013-11-03T09:39:55.027 回答
0

你有一个像这样的包含树,这会给你带来问题:

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

于 2013-11-03T09:51:25.533 回答