我有一個鏈接串列,其中包含指向第一個和最后一個節點的指標以及指示串列中有多少個節點的大小。我有一個函式可以回傳第一個節點中的資料。
我希望能夠使用queue1.front() = 3;. 但是,我越來越
lvalue required as left operand of assignment
編譯時出錯
Node班級
template<class T> class Node
{
public:
Node(const T& t);
Node(const Node&) = default; // Copy Constructor set to default
Node& operator=(const Node&) = default; // Assignment operator set to default
T getData();
private:
T m_data;
Node* m_nextNode;
};
template<class T> Node<T>::Node(const T& t)
{
this->m_data = t;
this->m_nextNode = nullptr;
}
template<class T> T Node<T>::getData()
{
return this->m_data;
}
Queue班級
template<class T> class Queue
{
public:
static const int DEFAULT_FIRST_INDEX = 0;
static const int SIZE_EMPTY = 0;
Queue();
Queue(const Queue&) = default; // Copy Constructor set to default
Queue& operator=(const Queue&) = default; // Assignment operator set to default
T front();
private:
Node<T>* m_head;
Node<T>* m_tail;
int m_size;
};
template<class T>
T Queue<T>::front()
{
if (this->m_size == Queue<T>::SIZE_EMPTY)
{
throw Queue<T>::EmptyQueue();
}
return this->m_head->getData();
}
uj5u.com熱心網友回復:
成員函式
T Node::getData() ...
T Queue<T>::front() ...
回傳 member 的副本m_data,這是一個臨時的r 值。為了使用賦值,您需要非常量左值參考限定T。因此,編譯器錯誤。
因此,您需要以下修復:
template<class T> class Node
{
public:
T& getData()
// ^^
{
return this->m_data;
}
const T& getData() const; // you might also need
// ^^^^^^^^^ ^^^^^
};
template<class T> class Queue
{
public:
T& front()
// ^^
{
// ....
return this->m_head->getData();
}
const T& front() const; // you might also need
// ^^^^^^^^ ^^^^^
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/481818.html
上一篇:當unique_ptr被銷毀時,如何檢索pclose的回傳值?
下一篇:BoostAsio超時方法
