C ++:类中结构的范围

时间:2013-07-26 06:46:17

标签: c++ class oop scope nested-class

我制作了一个类模板来实现一个基于节点的"堆栈名为"mystack" - :

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不应该可以访问代码的任何其他部分,除了类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  

有人可以告诉我们如何解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

正如评论中所提到的,我需要在temp的声明前插入关键字typename

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