C ++函数和类模板声明

时间:2014-07-10 04:29:09

标签: c++ function templates arraylist constructor

现在我正在试图看看为什么arrayList会出现错误,我不确定是不是因为我没有正确创建一个arrayList对象,因为我收到的错误是“未声明arrayList。这里是构造函数定义和声明的一两行代码。如果有人可以提供帮助,真的很感激。有人能告诉我是否在主程序中正确创建了arrayList对象吗?

#include "stdafx.h"
#include <iostream>
using namespace std;

template<typename Type> //Template class declaration. This needs to be here to be able to define the class templated. 

class arrayList

{

public:

arrayList<Type>::arrayList(Type size = 100);
                               //constructor
                               //Creates an array of size specified by the parameter
                               //size. The default array size is 100.
};

template<typename Type>
arrayList<Type>::arrayList(Type size)
{
    if(size < 0)
    {
        cout<<"The array size must be positive. Creating " << "an array of size 100. "<<endl;

        maxSize = 100;
    }
    else
       maxSize = size;

    length = 0;
    list = new int[maxSize];
}

//CONSTRUCTOR: Basically the size is capped off to 100 items, but user can add any number of items up to 100.

int main()
{
int num;//Numbers that will be prompted from the user 
int alternative; //New number to be added to the list 
int newnumber; //Used to be added in the arraylist
int newlocation;


    arrayList test; //This will be the tester Arraylist to test the methods
}

1 个答案:

答案 0 :(得分:1)

你不应该提前

arrayList<Type>::

在类定义中声明构造函数时。

另外,提供完整的错误消息,行号等内容可以帮助

使用该类型时,需要提供模板参数,如

arrayList<short> mylist;