2012-02-10 48 views
1

所以我一直tryind創建一個簡單的數組列表類,並得到了在一開始媒體鏈接卡住...林堅持與C++中的模板類

我的頭文件(我刪除了我的cpp文件,並仍然得到了同樣的信息)

#ifndef ARRAYLIST_H 
#define ARRAYLIST_H 

#include <iostream> 
using namespace std; 

template <typename T> 

class ArrayList { 
private: 
    T *arr; 
    int length; 

public: 
    ArrayList(); 

    void Insert(T item); 

    void Print(); 

    //friend &ostream operator<< (ostream &out, ArrayList &al); 
}; 

#endif 

和我的錯誤

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall ArrayList<int>::ArrayList<int>(void)" ([email protected]@@[email protected]) referenced in function _main 
1>C:\Users\Gannash\Desktop\Programming\C++WS\XMLReader\Debug\XMLReader.exe : fatal error LNK1120: 1 unresolved externals 
+1

嗯,你已經聲明瞭三個成員函數,在哪裏定義? – ildjarn 2012-02-10 23:08:47

回答

1

這就像你只是聲明瞭類的方法,而不是將它們定義

將所有定義放在標題中

+0

我actualy沒有聲明.cpp文件中的構造函數,但我沒有發佈它在這裏...仍然相同的錯誤信息 – 2012-02-10 23:20:41

0

您還沒有在.cpp文件中定義ArrayList(),Insert()和Print()。 您需要爲這些函數編寫代碼或將它們轉換爲純虛函數,或者virtual Print()=0;

1

如果您正在定義模板類,您應該提供所有的成員函數implmeentations內聯。缺少的ctor肯定是一個問題,但是當你真正使用你的課程時,會出現其他問題。另外,還有標準的容器提供你想要達到的東西,最值得注意的是std :: vector。

此外,在頭文件中使用名稱空間是一個過時的問題(或者至少極不鼓勵)。 您應該使用std :: qualification來代替,特別是您只需要一次。

0

,讓我們對錯誤信息:

unresolved external symbol "public: __thiscall ArrayList<int>::ArrayList<int>(void)" ([email protected]@@[email protected]) referenced in function _main 

unresolved external symbol =>有一些符號(這裏函數)聲明,但沒有定義

ArrayList<int>::ArrayList<int>(void) =>構造或以T實例化ArrayList類模板=詮釋

referenced in function _main =>有可能是像下面的代碼主():

ArrayList<int> IntList; 

的解決方案是提供構造的實施方案,可能如下:

ArrayList() : arr(0), length(0) {} 

類體內部。


順便說一句,請隨時查看您參考:

std::array 

    std::vector