2012-04-04 100 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

相关问题