const修饰的双向链表成员函数意外修改数据问题求助
问题原因及解决
核心原因:const成员函数对指针成员的限制范围
当成员函数被const修饰时,它仅保证当前类对象的成员变量本身不可被修改。对于List类里的Node* head这类指针成员,这个限制只作用于指针本身——你不能修改head指向的内存地址(比如不能写head = new Node(...)),但指针指向的Node对象本身并非const,所以可以随意修改head->data这类成员。
简单来说,在const成员函数里,head的类型等价于Node* const(指针本身不可变),而非const Node*(指向的对象不可变),这就是你能修改head->data的根本原因。
返回类型加const无效的原因
你尝试在返回类型前加const(比如const int search(...)),但这个const仅限制函数返回值的属性,和函数内部能否修改类对象的状态完全无关,所以不会改变结果。
修正方案
如果要让const成员函数无法修改Node的内容,需要让代码以const方式访问Node对象:
方式1:在函数内使用const Node*
int search(int val) const { const Node* current = head; if (current->data == val) // current->data = 12; // 此处会触发编译错误,无法修改const对象的成员 return current->data; }
方式2:封装Node的成员访问
将Node的data设为私有,提供const的getter函数,在const上下文中只能读取数据:
class Node { private: int data; public: Node* prev; Node* next; Node(int val) :data(val), next(NULL), prev(NULL) {} int getData() const { return data; } // const成员函数,仅用于读取data void setData(int val) { data = val; } // 非const成员函数,用于修改data };
此时在List的const成员函数里,只能调用head->getData(),无法直接修改data。
内容的提问来源于stack exchange,提问作者Huzaifa Malik
相关产品推荐
相关产品推荐

