使用 <list> (错误 C2760) 打印队列的元素
printing elements of a queue using <list> (error C2760)
尝试使用来自<list>
的双向链表实现队列,我的print()
函数收到以下错误:error C2760: syntax error: unexpected token 'identifier', expected ';'
队列类的代码为:
#ifndef DLL_QUEUE
#define DLL_QUEUE
#include <list>
#include <iostream>
using namespace std;
template<class T>
class Queue {
public:
Queue() {
}
void clear() {
lst.clear();
}
bool isEmpty() const {
return lst.empty();
}
T& front() {
return lst.front();
}
T dequeue() {
T el = lst.front();
lst.pop_front();
return el;
}
void enqueue(const T& el) {
lst.push_back(el);
}
void print() {
for (list<T>::const_iterator i = this->front(); i != this->back(); ++i)
cout << *i;
cout << "n";
}
private:
list<T> lst;
};
#endif
调用该类的主要方法是:
#include <iostream>
#include "genQueue.h"
using namespace std;
int main() {
//"genQueue.h"
Queue<int> *queue1 = new Queue<int>();
for (int k = 0; k < 100; k++)
queue1->enqueue(k);
queue1->print();
system("PAUSE");
return 0;
}
让我们好好看看print
函数:
void print() {
for (list<T>::const_iterator i = this->front(); i != this->back(); ++i)
cout << *i;
cout << "n";
}
您已经定义了一个成员方法T& Queue<T>::front
,您在编写this->front()
时尝试调用它。但是,T&
不能分配给List<T>::const_iterator
。此外,this->back()
尝试调用一个不存在的方法Queue<T>::back()
。
在尝试调用print()
之前,这些错误不会显现的原因是编译器只会在需要时实例化模板化代码。它不会尝试实例化您不调用的函数,因为该函数可能会毫无意义地无法针对您不想使用的某些类型进行编译。
如果目标是遍历成员列表的内容,您可以忘记上述所有复杂性,并使用万无一失的远程 for 循环,这要简单得多:
void print() {
for (const T& t : lst){
cout << t;
}
}
另一方面,没有理由使用new
动态分配队列。请注意,您不会delete
队列,因此会出现内存泄漏。如果可能,您应该按值将队列存储在堆栈上,以避免愚蠢的指针错误:
Queue<int> queue1;
for (int k = 0; k < 100; k++)
queue1.enqueue(k);
queue1.print();
如果确实需要队列存在于堆上,请考虑对自动管理其生存期和所有权的指针使用std::unique_ptr<Queue<T>>
或std::shared_ptr<Queue<T>>
。
另外,看看系统("暂停"(; - 为什么错了?
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 打印优先级队列
- 使用 <list> (错误 C2760) 打印队列的元素
- 在C++中打印对的优先级队列的所有值时出现问题
- 从 STL 优先级队列C++ (QtCreator) 打印结构
- 复制的队列更改 打印临时队列后队列的头部指针指向空 队列
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 队列快速排序不排序和打印随机字符串[C ]
- 打印队列元素的队列
- 为什么此代码无法打印队列中的所有值
- 我如何打印队列
- 尝试将队列打印为数组
- 按特定顺序打印队列
- 如何从FIFO队列阵列打印
- 如何打印队列的内容
- C++ 反向打印队列,而不使用堆栈或双向链表
- 以线程安全的方式每秒打印队列的当前元素数
- c++改变打印队列所有者
- c++-打印队列中的所有节点