C++模板数组,传递类型
C++ Template Array, passing type
我正在为一个类做一个项目,遇到了一些麻烦。我们的教授给了我们闲置代码
//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];
}
我认为这应该有效,但我似乎遇到的问题是,当我尝试调用主中的构造函数时
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’
任何帮助都将不胜感激!!
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
未在构造函数中使用。。。我猜你在这里错过了一些初始化。。。
对于眼前的问题:
template <typename type>
myList<type>::myList(int n) // declare as explicit!
{
length = n;
items = new type [n];
}
用法:
myList<int> list2(4);
但是你的代码已经有很多问题了,为什么toy在列表中分配数组还没有定论。
相关文章:
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 类型数组?
- 如何在使用 make_unique<T[]>() 制作的模板类型数组上使用 std::fill?
- 将基本类型数组中的内存重新用于不同(但仍然是基本)类型的数组合法吗
- 在C++中返回基元类型数组(Java比较)
- 如何返回 QVariant 类型数组
- 如何在本机 c++ jni 中实现 java 类型数组
- 模板类型数组的模板类型数组
- 如何确定未知类型数组的索引是否为空
- 复杂类型数组的静态初始化
- 访问基类型数组成员(Int-to-type习惯用法)
- 如何将 char 类型数组传递给函数并将第一个字符数组复制到第二个图表数组并使用 c++ 进行比较
- 如何在C 中制作结构类型数组
- 如何创建结构类型数组的地图对象
- C++类类型数组
- C++中的Matlab类型数组
- 节点C++插件 - 当类型数组(Float32Array)作为参数传递时,如何访问它?
- 如何将二维字符类型数组逐行保存到 c 中的.txt文件中
- C++:用户定义的类型数组出错
- 在双精度类型数组中使用 memset()