I have a linked list that contains a pointer to the first and last node and size which indicates how many nodes are there in the list. I have a function that returns the data in the first node.
I want to be able to change it using queue1.front() = 3;
. However, I am getting
lvalue required as left operand of assignment
error while compiling
Node
class
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
class
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();
}
CodePudding user response:
The member functions
T Node::getData() ...
T Queue<T>::front() ...
returning a copy of the member m_data
, which is an r-value temporary. In order to work with assignment, you need non-const l-value reference qualified T
. Hence, the compiler error.
Therefore, you need the following fix:
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
// ^^^^^^^^ ^^^^^
};