2013-11-03 208 views
1

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

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 
+1

删除.h文件中的所有循环包含:“employee.h”,“project.h”和“department.h” – Mercurial

+0

您正在使用正向声明的正确轨道上,但您只需要对文件。 – Damian

回答

3

您有周期性的#include s。

尝试从department.h删除#include "employee.h"#include "project.h"

反之亦然。

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; 

然后在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<...>