简体   繁体   English

C ++类模板错误

[英]C++ class template error

When I'm trying to use constructor of my class, I get the following errors: 当我尝试使用类的构造函数时,出现以下错误:

error C2955: 'myQueue' : use of class template requires template argument list 错误C2955:“ myQueue”:使用类模板需要模板参数列表

and

error C2512: 'myQueue' : no appropriate default constructor available. 错误C2512:“ myQueue”:没有适当的默认构造函数。

This is a header file: 这是一个头文件:

#ifndef myQueue_
#define myQueue_

template<typename type>
class myQueue{
public:
    myQueue();
    ~myQueue();
    type dequeue();
    void enqueue(type t);
private:
    int size;
    type* arr;
    int curSize;
};
#endif

And this is a cpp file. 这是一个cpp文件。

#include "myQueue.h"
#include "genlib.h"

template<typename type>
myQueue<type>::myQueue()
{
    size = 10;
    arr = new type[size];
}
template<typename type>
myQueue<type>::~myQueue()
{
    delete arr[];
    arr = NULL;
}

trying to use this class here. 尝试在这里使用此类。

 int main(){
    myQueue a = new myQueue();
 }

As explained by Wojciech Frohmberg, you must define the class in the *.h file instead of a *.cpp file, due to the fact that the code is really compiled when it's called with a specific type. 正如Wojciech Frohmberg所解释的那样,由于在使用特定类型调用代码时实际上已对其进行编译,因此必须在* .h文件而不是* .cpp文件中定义该类。

And your main is wrong. 而且您的主要观点是错误的。

int main(){
    myQueue<YourType>* a = new myQueue<YourType>;  // for pointer
    myQueue<YourType> b;  // for instance
 }

You're not using template properly. 您没有正确使用模板。 Template classes and methods should be declared in header file, only the full specialization should be stored in source files. 模板类和方法应该在头文件中声明,只有完整的专业化应该存储在源文件中。 Your header file should therefore look like: 因此,您的头文件应如下所示:

#ifndef myQueue_
#define myQueue_

template<typename type>
class myQueue{
public:
    myQueue();
    ~myQueue();
    type dequeue();
    void enqueue(type t);
private:
    int size;
    type* arr;
    int curSize;
};

template<typename type>
myQueue<type>::myQueue()
{
    size = 10;
    arr = new type[size];
}
template<typename type>
myQueue<type>::~myQueue()
{
    delete arr[];
    arr = NULL;
}

#endif

Also as Caduchon pointed you should declare type of your queue in a queue usage. 同样如Caduchon所指出的,您应该在队列使用情况中声明队列的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM