const函数修改双链表中的数据



我创建了一个双链表。在列表中,有一个函数是const,不应该修改对象。但是它被修改了,我不知道为什么。

#include<iostream>
using namespace std;
class Node {
public:
int data;
Node* prev;
Node* next;
Node(int val) :data(val), next(NULL), prev(NULL) {}
};
class List {
Node* head;
Node* tail;
public:
List() :head(NULL), tail(NULL) {}
void addToTail(int val) {
Node* temp = new Node(val);
if (head == NULL) {
head = temp;
tail = temp;
}
else {
tail = head;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = temp;
temp->prev = tail;
tail = temp;
}
}
int search(int val) const
{
if (head->data == val)
head->data = 12;
return head->data;
}
};
int main()
{
List l;
l.addToTail(1);
l.addToTail(2);
l.addToTail(3);
l.addToTail(4);
l.addToTail(5);
int c = l.search(1);
//c = 102;
cout << c;
}

现在我尝试在返回类型之前使用const,但显然这无关紧要。它不影响结果;在search(int val(函数中,我发送一个值来检查'head->data'等于'val',则不应修改'head->data=12',因为函数是常量。但它正在这样做。

仅成员函数的const限定符告诉编译器您不会修改this对象。

而您不需要这样做:您修改head->data,它是另一个对象。

如果您尝试重新分配变量headtail,则会出现不同的问题。

最新更新