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

时间:2018-10-05 05:52:36

标签: c++ queue doubly-linked-list

尝试使用myButton.setColorFilter(ContextCompat.getColor(context, R.color.Gray), android.graphics.PorterDuff.Mode.MULTIPLY); 中的双向链接列表来实现队列,而我的<list>函数遇到以下错误:print()

Queue类的代码为:

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

1 个答案:

答案 0 :(得分:2)

我们来看看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()之前,这些错误不会显现的原因是,编译器仅在需要时才会实例化模板化代码。它不会尝试实例化您不调用的函数,因为该函数可能无意义地无法针对某些您不想使用的类型进行编译。


如果目标是遍历成员列表的内容,则可以忽略上述所有复杂性,并使用简单得多的ranged for loop,这很简单:

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>>来自动管理其生存期和所有权的指针。

另外,请看一下system(“pause”); - Why is it wrong?

相关问题