C++ : Scope of struct inside a class

标签 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  

谁能告诉我如何解决这个问题?

最佳答案

如评论中所述,我需要插入关键字 typename在 temp 声明前 -:

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

关于C++ : Scope of struct inside a class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17874652/

相关文章:

c++ - 无法构建 32 位 Mongodb C++ 驱动程序

jquery - 如何在两个表行之间插入另一个表行?

java - 不暴露 'internal structure' 是什么意思? (迭代器)

java - 从 Java 中返回的方法对象创建新对象

c++ - 具有堆对象和销毁冲突的数据类型的浅拷贝

c++ - 0x800a1421 HRESULT 是什么意思?

c++ - 如何将异常报告给 boost::future?

c# - 遍历具有相同基类的对象列表并提取某个类?

c++ - 将未使用的类数据成员存储在磁盘上

MATLAB 对象属性可见但不可修改