Mình có một bài toán như sau.
- Xây dựng một lớp node:
Code:
#include <iostream>
using namespace std;
//Basic Doubly Linked List node class.
class DLLNode
{
public:
DLLNode() //Default Constructor
{
p_data = 0; //No data.
p_next = NULL; //New node always has a NULL next node.
p_prev = NULL; //New node always has a NULL previous node.
}
DLLNode(unsigned int data) //Constructor
{
p_data = data; //No data.
p_next = NULL; //New node always has a NULL next node.
p_prev = NULL; //New node always has a NULL previous node.
}
unsigned int data(void) const //Retreive the data of the node. Constant function.
{
return p_data;
}
DLLNode* prev(void) const //Retreive the preivous pointer of the node. Constant function.
{
return p_prev;
}
DLLNode* next(void) const //Retreive the previous pointer of the node. Cosntant function.
{
return p_next;
}
void setdata(unsigned int data) //Set the data of the node.
{
p_data = data;
}
void setprev(DLLNode* prev) //Set the previous pointer of the node.
{
p_prev = prev;
}
void setnext(DLLNode* next) //Set the next pointer of the node.
{
p_next = next;
}
private:
unsigned int p_data; //Data stored by the node. protected.
DLLNode* p_prev; //Pointer to the next node. protected.
DLLNode* p_next; //Pointer to the previous node. protected.
};
ostream& operator << (ostream& out, DLLNode& node) //Output the data of a node.
{
out << node.data() << " "; //Output the data of the node, followed by a space.
return out; //Return the output stream.
}
- Sau đó, mình thêm vào lớp này một định nghĩa toán tử ++ như sau:
Code:
void operator ++ ()
{
this = p_next;
}
- Khi dịch chương trình (có đoạn code vừa thêm vào) thì trình biên dịch báo lỗi "error C2106: '=' : left operand must be l-value". Theo mình hiểu thì nguyên nhân là do kiểu của con trỏ this lúc này là "DDLNode* const". Làm cách nào để có thể khắc phục lỗi này đây? Ai giúp mình với !
- Mục đích của mình là muốn tạo ra một danh sách, trong đó có con trỏ p_root (kiểu Node*) nằm ở đầu danh sách. Sau đó tạo ra 1 con trỏ khác là p_current. Lúc đầu ta gán p_current = p_root, khi thực hiện phép toán p_current++ thì p_current sẽ trỏ sang p_root->p_next,... cứ tiếp tục như vậy.