我創建了一個雙向鏈表。在串列中,有一個函式是 const,不應該修改物件。但它是modifiedind 我不知道為什么。
#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。但它正在這樣做。
uj5u.com熱心網友回復:
成員函式的const限定符僅告訴編譯器您不會修改this物件。
你不這樣做:你修改head->data哪個是另一個物件。
如果您嘗試重新分配變數head或tail.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/516823.html
標籤:C 指针链表
下一篇:沒有多載函式“std::vector<_Ty,_Alloc>::erase[with_Ty=Enemy*,_Alloc=std::allocator<Enemy*>]”的實體與
