C++:类内部结构的作用域
C++ : Scope of struct inside a class
我制作了一个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
之外,结构mystack_node
不应该对代码的任何其他部分都是可访问的。所以我尝试了以下变通方法-:
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
谁能告诉我如何解决这个问题吗??
如注释中所述,我需要在temp-:的声明前面插入关键字typename
typename mystack<T>::mystack_node *temp = a.stack_top;
相关文章:
- 未在作用域中声明unordered_map
- 有没有一种方法可以在编译时获得作用域类名
- C++quit()函数中可能存在作用域问题
- 未在此作用域OpenCV3.4中声明cvSaveImage
- 如何声明在函数作用域中定义的结构
- 变量声明中结构的作用域解析是什么意思
- 为什么离开作用域后仍然有对结构的有效访问
- 想知道C++中的结构和函数的作用域
- 结构c++中的作用域
- 返回具有引用父作用域中变量的函数成员的结构
- 类和作用域中的公共结构
- C++:类内部结构的作用域
- c++/结构的作用域
- 在两个结构(函子)中理解typedef的作用域
- 被视为依赖作用域的函数模板的函数作用域结构体的静态成员函数
- 返回指向类定义的结构体的指针,多个作用域操作符
- 内部结构在非命名空间作用域中的显式专用化
- 是成员声明`decltype(name)name;`在第一个名称引用封闭作用域的本地结构中允许
- 当结构未解析为类型和作用域问题时的c++错误
- 为结构的数组创建指针作用域和构造函数