2014-03-25 58 views
2

我想編譯我的代碼,但我得到一個類的錯誤。其中一個類編譯得很好(Example.h),但另一個(Name.h)一直給我這個類沒有名稱類型錯誤。我認爲這與循環依賴有關,但如何在沒有前向減速的情況下解決這個問題?類名不聲明類型C++

Name.h

#ifndef _NAME 
#define _NAME 
#include <iostream> 
#include <string> 
using namespace std; 
#include "Example.h" 
class Name{ 
}; 
#endif 

example.h文件

#ifndef _EXAMPLE 
#define _EXAMPLE 
#include <iostream> 
#include <string> 
using namespace std; 
#include "Name.h" 
class Example{ 

}; 
#endif 

我看到了一個有關使用正向減速後,但我需要從實例類訪問承包商,客人..

+1

您不能在'A.h'中的'B.h'和'B.h'中包含'A.h'。它確實是循環依賴。您可以嘗試前進類的聲明。 – Mikhail

+0

但是將向前聲明讓我訪問其他類的成員函數? – user2351234

+0

與問題無關,但由於您(大概)使用現代C++編譯器,因此可以避免使用過時的'#ifndef _EXAMPLE #define _EXAMPLE#endif'事物。只需使用'#pragma once'。 (http://en.wikipedia.org/wiki/Pragma_once) –

回答

1

看,這裏您包括#include "Example.h"Name.h#include "Name.h" in Example.h。假設編譯器編譯Name.h文件首次如此_NAME現在定義,然後它會嘗試編譯Example.h這裏編譯器要包括Name.hName.h的內容將不會被列入,因爲_NAMEExample.h已經被定義,因此class Name是不是裏面Example.h定義。

你可以明確地做內部Example.h

2

class Name;向前聲明你有循環依賴,其中每個標題嘗試包括其他的,這是不可能的。結果是一個定義在另一個定義之前結束,而第二個定義的名稱在第一個定義中不可用。

如果可能,聲明每個類,而不是包括整個頭:

class Example; // not #include "Example.h" 

你將不能夠這樣做,如果一個類實際上包含(或繼承)其它;但是這將允許在許多聲明中使用該名稱。由於兩個類別不可能包含另一個類別,因此您可以至少完成其中一個類別(或者完全刪除#include),這樣可以打破循環依賴關係並解決問題。

另外,不要使用reserved names_NAME,並且不pollute the global namespaceusing namespace std;

0

試試這個:

Name.h

#ifndef NAMEH 
#define NAMEH 
#include <iostream> 
#include <string> 
using namespace std; 

//#include "Example.h" 
class Example; 

class Name{ 
}; 
#endif 

Name.cpp

#include "Name.h" 
#include "Example.h" 
... 

example.h文件

#ifndef EXAMPLEH 
#define EXAMPLEH 
#include <iostream> 
#include <string> 
using namespace std; 

//#include "Name.h" 
class Name; 

class Example{ 

}; 
#endif 

實施例。cpp

#include "Example.h" 
#include "Name.h" 
...