我遇到了返回值/引用的问题。我正在编写一个模板(队列),并且Front()
函数应该从队列的前面返回元素,但我得到一个错误 - No viable conversion from 'Queue<int>::Node' to 'const int'
。当我删除时const
,我得到Non-const lvalue reference to type 'int' cannot bind to a value of unrelated type 'Queue<int>::Node'
了,而其他参考/无参考变体,const/no const 给了我这两个错误中的任何一个。我错过了什么?
#include <iostream>
using namespace std;
template <typename T>
class Queue
{
friend ostream& operator<< (ostream &, const Queue<T> & );
private:
class Node
{
friend class Queue<T>;
public:
Node(const T &t): node(t) {next = 0;}
private:
T front;
T back;
T node;
Node *next;
};
Node *front;
Node *back;
public:
Queue() : front(0), back(0) {}
~Queue();
bool Empty()
{
return front == 0;
}
T& Front()
{
if (Empty())
cout << "Очередь пуста." << endl;
else
{
T const & temp = *front; // error here
return temp;
}
}
/* ... */
};
template <class T> ostream& operator<< (ostream &, const Queue<T> & );
int main()
{
Queue<int> *queueInt = new Queue<int>;
for (int i = 0; i<10; i++)
{
queueInt->Push(i);
cout << "Pushed " << i << endl;
}
if (!queueInt->Empty())
{
queueInt->Pop();
cout << "Pop" << endl;
}
queueInt->Front();
return 0;
}