2012-04-04 47 views
0

我寫了一個類,它需要兩個組成部分,一個隨機類類型T和一個整數,我實現它像以下: 在Test.h,如:如何用C++中的泛型類創建對象?

template <class A, int B>class Test { // two components, 
    private: 
     A first; 
     int second; 

    public: 
     Test(); 
     Test (A,int); 
    } 

在Test.cpp的我所做的:

template <class T,int i> Test<T,i>::Test() {} 
    template <class A,int i>Test<A,i>::Test(T a, int b):first(a) {second=b;} 

但在主要功能:

Test<int, int > T1; //It can not be passed 
    Test<int, 4> T2; //It can not be passed 
    int x = 8; 
    Test<int, x> T3 (3,4);// can not be passed 

我怎樣才能申報對象instanc e從上面的泛型類?

+2

感嘆。 http://www.parashift.com/c++-faq-lite/templates.html#faq-35.15。 – 2012-04-05 00:02:14

+3

正確的術語是「類模板」。在這種情況下,「通用」一詞有點危險,因爲它在其他語言中有着非常不同的含義。 – 2012-04-05 00:02:57

+0

我如何從Test類聲明一個對象?這是個問題。夥計,我需要它....請 – ToBeGeek 2012-04-05 00:19:09

回答

0

您忘記了類模板定義末尾的分號。

0
template <class T,int i> Test<T,i>::Test() {} 
template <class A,int i>Test<A,i>::Test(T a, int b):first(a) {second=b;} 

你需要把這兩個模板函數定義在頭而非.cpp - 需要被提供給調用這些函數,而不僅僅是聲明所有編譯單元的實際代碼。

Test<int, int > T1; //It can not be passed 

這是無效的,第二int是一種類型,但模板期望一個int

Test<int, 4> T2; //It can not be passed 

有什麼錯

int x = 8; 
Test<int, x> T3 (3,4);// can not be passed 

你需要做的第一這些行的編號爲static const x = 8(即,使編譯時常量爲x)使其可用作模板參數

在類定義的末尾還有缺失的分號。

+0

測試 T2;這是錯誤的。它不能編譯... – ToBeGeek 2012-04-05 00:34:54

+0

@ user1314029有什麼錯誤?它爲我固定其他錯誤 – je4d 2012-04-05 00:44:12

+0

用於建築x86_64的未定義符號後: 「測試 ::測試()」,從引用: _main在main.o中 LD:符號(S)沒有發現建築x86_64的 鐺:錯誤:鏈接器命令失敗,退出代碼1(使用-v來查看調用) – ToBeGeek 2012-04-05 00:46:29

相關問題