2010-06-06 72 views
0

我發現此矢量模板類實現,但它不能在XCode上編譯。創建模板類時出錯

頭文件

// File: myvector.h 

#ifndef _myvector_h 
#define _myvector_h 

template <typename ElemType> 
class MyVector 
{ 
public: 
    MyVector(); 
~MyVector(); 
int size(); 
void add(ElemType s); 
ElemType getAt(int index); 

private: 
ElemType *arr; 
int numUsed, numAllocated; 
void doubleCapacity(); 
}; 

#include "myvector.cpp" 

#endif 

實現文件:

// File: myvector.cpp 

#include <iostream> 
#include "myvector.h" 

template <typename ElemType> 
MyVector<ElemType>::MyVector() 
{ 
arr = new ElemType[2]; 
numAllocated = 2; 
numUsed = 0; 
} 

template <typename ElemType> 
MyVector<ElemType>::~MyVector() 
{ 
delete[] arr; 
} 

template <typename ElemType> 
int MyVector<ElemType>::size() 
{ 
return numUsed; 
} 

template <typename ElemType> 
ElemType MyVector<ElemType>::getAt(int index) 
{ 
if (index < 0 || index >= size()) { 
    std::cerr << "Out of Bounds"; 
    abort(); 
} 
return arr[index]; 
} 

template <typename ElemType> 
void MyVector<ElemType>::add(ElemType s) 
{ 
if (numUsed == numAllocated) 
    doubleCapacity(); 
arr[numUsed++] = s; 
} 

template <typename ElemType> 
void MyVector<ElemType>::doubleCapacity() 
{ 
ElemType *bigger = new ElemType[numAllocated*2]; 
for (int i = 0; i < numUsed; i++) 
    bigger[i] = arr[i]; 
delete[] arr; 
arr = bigger; 
numAllocated*= 2; 
} 

如果我嘗試按原樣編譯,我得到以下錯誤: 「的重新定義 'MyVector :: MyVector()' 「 每個成員函數(.cpp文件)都顯示相同的錯誤。

爲了解決這個問題,我取消了對.cpp文件中「的#include‘myvector.h’」,但現在我得到一個新的錯誤:之前‘<’ 「預期的構造函數,析構函數或類型轉換令牌」。 每個成員也會顯示一個類似的錯誤。

有趣的是,如果我將所有的.cpp代碼移動到頭文件,它編譯得很好。這是否意味着我不能在單獨的文件中實現模板類?

回答

0

將模板放在頭文件中總是一個好主意。這樣你就不會用相同的實例等的多個定義來搞亂鏈接器。

當然還有圓形包含:)。

0

首先,你必須

#include "myvector.cpp" 

其創建的文件之間的循環引用。只是擺脫它。

另一個問題是,您正在.cpp文件中定義模板類。模板定義只允許在頭文件中。這可能有辦法,但對於g ++(XCode使用的),這就是cookie如何崩潰。

+1

這並不是說它們不在* .cpp文件中。如果以這種方式完成編譯和鏈接,就會遇到與模板如何工作相關的問題(以及缺少'export'關鍵字的體面支持)。 – Pieter 2010-06-06 15:38:19