模板函数参数有什么问题

what is wrong with the template function parameter

本文关键字:什么 问题 参数 函数      更新时间:2023-10-16

嗨,我是模板新手。只是想知道如何正确编译程序。

 template<class t>
 class node{
    public: 
       t val;
       node(t v):val(v){}
 };
 template<class t>
 class stack{
   private: 
     stack *next;
     static stack *head;
     static int top;
   public:  
     void push(node *n);
     node* pop();
 };
 template<class t>
 int stack<t>::top=0;
 template<class t>
 stack<t>* stack<t>::head=NULL;
 template<class t>
 void stack<t>::push(node<t>* n)   //Error the push function is not defined properly
 {
 }

 int main(int argc, char *argv[])
 {
    node<int> n1(5);
    return 0;
 }

程序给出错误

  stack<t>::push' : redefinition; different basic types
     nw.cpp(14) : see declaration of 'stack<t>::push'

提前感谢

类模板node需要模板参数

在以下位置使用node<t>

CCD_ 3和CCD_

声明:

void push(node *n);

应该是:

void push(node<t> *n);
  public:  void push(node *n);

应该是

  public:  void push(node<t> *n);

node是一个类模板,因此即使在声明中也需要它的模板参数:

void     push(node<n> *n);
node<t>* pop();

唯一可以在参数声明中省略模板参数的情况是当声明出现在类作用域本身中时。在这种情况下,node被称为注入的类名

此外,正如注释所指出的,headtop不应该是静态数据成员。这会抑制独立堆栈实例的创建,并且在使用它们时可能会造成很多混乱。相反,让它们成为非静态数据成员,这样它们就只引用正在使用的实例。