使用 <list> (错误 C2760) 打印队列的元素

printing elements of a queue using <list> (error C2760)

本文关键字:打印 队列 C2760 元素 lt list gt 使用 错误      更新时间:2023-10-16

尝试使用来自<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>>

另外,看看系统("暂停"(; - 为什么错了?