我遇到了返回值/引用的問題。我正在寫一個模板(隊列),並且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給出了這兩個錯誤中的任何一個。我錯過了什麼?沒有從'Template <int> :: Memberclass'到'const int'的可行轉換
#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;
}
如果有人在空隊列中調用'Front'(或拋出異常),則需要返回_something_。否則,你會得到未定義的行爲。 – Mat
@Mat感謝您指出!我完全忘記了回來。 – Kaworu
您的編譯器也可以指出它(啓用警告) - 雖然有時也需要啓用優化(需要流分析)。 – Mat