2013-11-03 62 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<...>