C++:[class]未在此作用域中声明
C++: [class] was not declared in this scope
-----------------------------------使用.h-------------------
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
#include "MyException.h"
using namespace std;
template<class T>
class Queue;
template<class T>
ostream& operator<<(ostream&,Queue<T>&);
template<class T>
class Queue
{
public:
friend ostream& operator<< <T>(ostream&,Queue<T>&);
Queue();
Queue(const Queue<T>& other);
Queue<T>& operator=(const Queue<T>& other);
~Queue();
void enqueue(const T& el);
T dequeue();
void increasePriority(const T& el);
bool isEmpty();
private:
class Node
{
public:
Node(const T& data, Node* n = 0)
{
element = data;
next = n;
}
T element;
Node* next;
};
Node* head;
};
#include "Queue.C"
#endif
我们根本不允许更改.h(以上(文件。
---------------------队列.C-------------------
#include "Queue.h"
template<class T>
ostream& operator << (ostream &strm, Queue<T> &obj)
{
if (obj.isEmpty())
{
strm << "[]";
return strm;
}
else
{
strm << '[';
//line 28
Node* tmp = new Node();
tmp = obj.head;
strm << tmp.element + ',';
while (tmp->next != 0)
{
tmp = tmp->next;
if (tmp-next != 0)
{
strm << tmp.element + ',';
}
else
{
strm << tmp.element;
}
}
strm << ']';
delete [] tmp;
tmp = 0;
return strm;
}
return strm;
}
//...more code
Queue::Queue()
{
//line 54
head = new Node();
}
因此,从该代码中,我收到的一些错误如下:
Queue.C: In function ‘std::ostream& operator<<(std::ostream&, Queue<T>&)’:
Queue.C:28: error: ‘Node’ was not declared in this scope
Queue.C:28: error: ‘tmp’ was not declared in this scope
Queue.C:28: error: expected type-specifier before ‘Node’
Queue.C:28: error: expected ‘;’ before ‘Node’
Queue.C:34: error: ‘next’ was not declared in this scope
Queue.C: At global scope:
Queue.C:54: error: ‘head’ was not declared in this scope
Queue.C:54: error: expected type-specifier before ‘Node’
Queue.C:54: error: expected ‘;’ before ‘Node’
您将Queue.h
包含在Queue.C
中,反之亦然。您不应该在Queue.C
中包含Queue.h
,因为您希望整个实现可以从标头访问。
接下来,Node
在Queue
中声明,因此在实现中必须以Queue
类模板的作用域为前缀:
Queue<T>::Node ...; // instead of Node
您必须在Node
前面加上它在其中定义的范围,即Queue
Queue<T>::Node* tmp = new Queue<T>::Node();
否则编译器不知道您指的是哪种Node
类型。
但在下一行中,您将用obj.head
覆盖tmp
指针,并丢失新创建的Node
。这将导致内存泄漏。在任何情况下,您都不需要在运算符中创建新的Node
,它只输出一个Queue。
再往下,你
delete [] tmp;
它会删除队列中的最后一个元素。我想,您不应该在这个输出操作符中以任何方式修改Queue。
这就引出了下一点,这个操作符应该被声明为
friend ostream& operator<< <T>(ostream&, const Queue<T>&);
以避免意外修改Queue对象。
相关文章:
- 未在作用域中声明unordered_map
- 未在此作用域OpenCV3.4中声明cvSaveImage
- 未在此作用域中声明的函数和变量 (C++)
- 函数未在作用域中声明 / 如何结合使用 header.h、header.cpp 和 main.cpp?
- 重载时未在 C++ 的作用域错误中声明
- 在 C++ 中使用 "transform" 会给出一个错误,指出这未在作用域中声明
- Tictactoe 游戏变量未在作用域中声明
- 当变量在多个函数作用域中使用时,我应该在类 private 中声明该变量吗?
- 如何在C++中嵌套词法作用域可访问的作用域中声明静态信息?
- gets()未在作用域中声明
- 在C++14中,在哪个作用域中声明了重新声明枚举的非范围枚举器
- C++11 外部作用域变量声明为 auto
- 未在此作用域中声明类 (c++)
- 如何声明在函数作用域中定义的结构
- 未在此作用域中声明函数,即使存在头文件也是如此
- 变量声明中结构的作用域解析是什么意思
- 在C++中,在给定的相同作用域内声明相同的变量名
- 我可以使用相同的名称为周围作用域中的类型声明成员类型别名吗
- 类未在作用域中声明,但已声明该类
- 使用新的外部函数作用域声明和初始化变量