简体   繁体   中英

Member function definition outside of class body results in error

I am pretty new to the concept of templates. Am I missing something?

#ifndef STACK_H
#define STACK_H

template < class T>
class Stack{
private:
  struct node {
    T data;
    node* next;
  };
  node * top;
  //node* getNewNode(T num);
};

//template <class T>
//(node*)Stack<T> :: getNewNode(T num){
//    node *    temp = new node;
//      temp->data = num;
//      temp->next = NULL;
//      return temp;
//  }

#endif

When I uncomment the function getNewNode and commend the corresponding statement to getNewNode function, complier gives error like Why is my function getNewNode not working as expected. Where did I go wrong?

Error   7   error C2470: 'Stack<T>::getNewNode' : looks like a function
definition, but there is no parameter list; skipping apparent
body    c:\users\nitinjose\documents\visual studio
2010\projects\templatequeue\templatequeue\stack.h   26  1   TemplateQueue
Error   2   error C4430: missing type specifier - int assumed. Note: C++
does not support default-int    c:\users\nitinjose\documents\visual
studio
2010\projects\templatequeue\templatequeue\stack.h   26  1   TemplateQueue
Error   5   error C2146: syntax error : missing ')' before identifier
'num'   c:\users\nitinjose\documents\visual studio
2010\projects\templatequeue\templatequeue\stack.h   26  1   TemplateQueue

The specification of the return value is wrong. Try this

template <class T>
typename Stack<T>::node* Stack<T> :: getNewNode(T num){
    // ...
}

Defining a member function outside of a class body changes the rules for what names are accessible at that point slightly. In your case the compiler has no idea what node is. You need to tell him that the node* is actually in the class Stack<T> , eg typename Stack<T>::node . The typename is necessary here, because node is a dependent name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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