2013-07-26 3 views
2

Я сделал шаблон класса для реализации «узел на основе» Стек назван "mystack" -:C++: Область структуры внутри класса

template<typename T> class mystack; 
template<typename T>ostream& operator <<(ostream& out,const mystack<T> &a); 

template<typename T> struct mystack_node // The data structure for representing the "nodes" of the stack 
{ 
    T data; 
    mystack_node<T> *next; 
}; 
template<typename T> class mystack 
{ 
    size_t stack_size; // A variable keeping the record of number of nodes present in the stack 
    mystack_node<T> *stack_top; // A pointer pointing to the top of the stack 
    /* 
    ... 
    ...(The rest of the implementation) 
    ... 
    */ 
    friend ostream& operator << <T> (ostream&,const mystack&); 
}; 
template<typename T>ostream& operator <<(ostream& out,const mystack<T> &a) // Output operator to show the contents of the stack using "cout" 
{ 
    mystack_node<T> *temp=a.stack_top; 
    while(temp!=NULL) 
    { 
     out<<temp->data<<" "; 
     temp=temp->next; 
    } 
    return out; 
} 

Но то, что я на самом деле хочу, что структура mystack_node не должен» t быть доступным для любой другой части кода, за исключением класса mystack. Так что я попытался следующий обходной путь -:

template<typename T> class mystack; 
template<typename T>ostream& operator <<(ostream& out,const mystack<T> &a); 
template<typename T> class mystack 
{ 
    struct mystack_node // The data structure for representing the "nodes" of the stack 
    { 
     T data; 
     mystack_node *next; 
    }; 
    size_t stack_size;  // A variable keeping the record of number of nodes present in the stack 
    mystack_node *stack_top;  // A pointer pointing to the top of the stack 
    /* 
    ... 
    ...(The rest of the implementation) 
    ... 
    */ 
    friend ostream& operator << <T> (ostream&,const mystack&); 
}; 
template<typename T>ostream& operator <<(ostream& out,const mystack<T> &a) // Output operator to show the contents of the stack using "cout" 
{ 
    mystack<T>::mystack_node *temp=a.stack_top; 
    while(temp!=NULL) 
    { 
     out<<temp->data<<" "; 
     temp=temp->next; 
    } 
    return out; 
} 

Но я получаю следующее сообщение об ошибке компилятора -:

In function ‘std::ostream& operator<<(std::ostream&, const mystack<T>&)’: 
error: ‘temp’ was not declared in this scope 

Может кто-нибудь, пожалуйста, как решить эту проблему ??

+3

Вам нужно ключевое слово 'typename' перед объявлением' temp' : 'typename mystack :: mystack_node * temp = a.stack_top;' – jogojapan

+1

Аналогичный вопрос: http://stackoverflow.com/questions/1301380/g-is-not-a-type-error – jogojapan

+1

@jogojapan, вы должны сделать это ответ на вопрос. – Pete

ответ

2

Как уже упоминалось в комментариях, мне нужно было вставить ключевое слово typename перед объявлением температуры -:

typename mystack<T>::mystack_node *temp = a.stack_top;

Смежные вопросы