问题描述
我正在尝试学习c ++中的模板用法.我创建了一个在队列类实现中使用的struct节点,但出现编译器错误:错误",成员函数bool MyQueue :: add(T data)中qnode之前的预期类型说明符
I am trying to learn templates usage in c++. I have created a struct node which I am using in queue class implementation but I am getting compiler error:Error" expected type specifier before qnode in member function bool MyQueue::add(T data)
#include <iostream>
using namespace std;
template <typename T>
struct qnode {
qnode* Node;
T data;
};
template <class T>
class MyQueue {
qnode<T>* front;
qnode<T>* end;
public:
MyQueue() {
front=NULL;
end=NULL;
}
bool add (T n);
T get(void);
bool empty(void)
{
if ( front == NULL)
return true;
else
return false;
}
size_t size(void)
{
}
};
template <typename T>
bool MyQueue<T>::add ( T n)
{
qnode<T>* temp = new qnode;
temp->data = n;
temp->Node = NULL;
if ( front == NULL )
{
cout << "Adding front qnode " << endl;
front = end= temp;
// front->Node = end;
return true;
}
cout << "Adding qnode " << endl;
end->Node = temp;
end=temp;
//delete temp;
return true;
}
我期待着一个很好的解释,说明如何在这种嵌套实现中解析模板参数.
I am looking forward for a nice explanation for how template parameters get resolved in such nested implementation.
推荐答案
您的 new
语法错误.
qnode<T>* temp = new qnode;
应该是
qnode<T>* temp = new qnode<T>();
请记住,没有模板参数的模板类对编译器毫无意义.每当您输入qnode时(在初始声明之后),您还需要输入其模板参数!
Remember, a template class without template parameters is meaningless to the compiler. Whenever you type qnode (after the initial declaration), you need to type its template parameters as well!
这篇关于在模板类实现中使用结构模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!