1

我正在为一个班级做一个项目,遇到了一些麻烦。我们的教授给了我们休闲密码

//myList.h file
template <class type>
class myList
{
    protected:
        int length;         //the number of elements in the list
        type *items;        //dynamic array to store the elements

public:
    ~myList();  
        //destructor for memory cleanup
        //Postconditions: Deallocates the memory occupied by the items array

    myList();   
        //default constructor
        //Postconditions: creates items array of size 0 and sets size to zero

    myList(int n, type t);  
        //assignment constructor
        //Postconditions: creates items array of size n and type t, sets length to n
}

那么我为 myList(int m, type t) 创建的构造函数代码是:

template <typename type>
myList<type>::myList(int n, type t)
{
   length = n; 
   items = new  t [n]; 
   }

我认为应该可以,但是我似乎遇到的问题是当我尝试在我的 main 中调用构造函数时

myList list2(4, int); 

我收到以下错误

In file included from testmyList.cpp:1:0:
myList.h: In constructor ‘myList<type>::myList(int, type)’:
myList.h:118:17: error: expected type-specifier before ‘t’
myList.h:118:17: error: expected ‘;’ before ‘t’
testmyList.cpp: In function ‘void test2()’:
testmyList.cpp:17:9: error: missing template arguments before ‘list2’
testmyList.cpp:17:9: error: expected ‘;’ before ‘list2’

任何帮助将不胜感激!!

4

2 回答 2

0

new期待一个类型。不是变量

template <typename type>
myList<type>::myList(int n, type t)
{
   length = n; 
   items = new  type[n]; 
}

请注意,类声明的注释是错误的。你应该有:

myList(int n, type t);  
    //assignment constructor
    //Postconditions: creates items array of size n and type **type**, sets length to n

顺便说一句,您的构造函数中未使用该值...我 您在这里缺少一些初始化...t

于 2013-06-23T18:38:50.737 回答
0

对于眼前的问题:

template <typename type>
myList<type>::myList(int n)  // declare as explicit!
{
  length = n; 
  items = new  type [n]; 
}

用法:

myList<int> list2(4); 

但是你的代码已经有很多问题了,为什么玩具在列表中分配数组是没有意义的。

于 2013-06-23T18:41:43.483 回答