[英]Implementation vs. Header File
我已經編寫了程序,當我將所有內容都保留在頭文件中並擁有主文件時,它就可以工作。 我現在將它們分成實現文件,但是Eclipse一直給我錯誤。 它在構造函數和函數的每個開頭都給我錯誤。 它對所有人都說:“(構造函數或方法的名稱)的重新定義,以前在這里聲明過”。 我在做什么錯,因為它在頭文件中起作用?
#include "KeyValuePair.h"
template<typename Key,typename Value>
KeyValuePair<Key,Value>::KeyValuePair()
{ // error here
}
template<typename Key,typename Value>
void KeyValuePair<Key,Value>::setPair(Key key, Value value)
{ // error here
pairKey = key;
pairValue = value;
}
template<typename Key,typename Value>
Key KeyValuePair<Key,Value>::getKey() const
{ // error here
return pairKey;
}
template<typename Key,typename Value>
Value KeyValuePair<Key,Value>::getValue() const
{ // error here
return pairValue;
}
頭文件:
#ifndef _KEYVALUEPAIR_H_
#define _KEYVALUEPAIR_H_
template<typename Key,typename Value>
class KeyValuePair
{
private:
Key pairKey;
Value pairValue;
public:
KeyValuePair();
void setPair(Key key,Value value);
Key getKey() const;
Value getValue() const;
};
#include "KeyValuePair.cpp"
#endif
現在,您的KeyValuePair.h文件在底部具有#include KeyValuePair.cpp
。 KeyValuePair.cpp還#include頭文件。 頭文件具有通常的“保護”(#ifndef _KEYVALUEPAIR_H_),以防止被多次包含,但您的CPP文件則沒有。 因此,當您嘗試編譯CPP文件時,它會拉入H文件,該文件又會拉入CPP文件。 因此,多重定義錯誤。
對您來說, 最簡單的解決方案(但不一定是最正確的解決方案)是從KeyValueHeader.cpp文件頂部刪除#include "KeyValuePair.h"
行。
我懷疑您是在嘗試在Makefile中實際編譯KeyValuePair.cpp,而您不需要(也不應該這樣做)。 您只需要具有需要您的模板類的源文件即可#include "KeyValuePair.h"
。
模板的標准做法是將聲明和實現保留在同一頭文件中-隱式避免了此類問題。 內聯到模板類聲明中並內含在單個頭文件中的模板類方法的實現並不少見。 破壞了您所學到的關於將接口與實現分離的所有知識,但是更易於使用。
您需要將模板的所有代碼放入按需編譯的頭文件中。
請參閱模板文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.