[英]Non-const pointer to this in const member function
I'm trying to implement a last() function for a linked list, which, when called from any node in the list, will return the final node in the list: 我正在尝试为链接列表实现last()函数,当从列表中的任何节点调用该函数时,它将返回列表中的最后一个节点:
template <typename T>
LinkedList::LinkedListElement<T>* LinkedList::LinkedListElement<T>::last () const {
LinkedList::LinkedListElement<T>* p = this;
while(p->next) {
p = p->next;
}
return p;
}
Since only returning the last node shouldn't change the list at all, I thought it made sense to make it a const function, although once the end user has that node, he can certainly modify the list by calling other functions, such as insert. 由于仅返回最后一个节点根本不应该更改列表,因此我认为将其设为const函数是有意义的,尽管最终用户拥有该节点后,他当然可以通过调用其他函数(例如insert)来修改列表。 。
The compiler complains on line 3, that I'm trying to convert a const pointer to a non-const one. 编译器在第3行抱怨说,我正在尝试将const指针转换为非const指针。 Apparently, making my function const caused
this
to become a constant pointer. 显然,将我的函数设为const会使
this
成为常量指针。 So I've tried making pa pointer to const data, but then the line return p;
因此,我尝试使pa指针指向const数据,但随后该行
return p;
gives the same error, that I'm trying to convert from const to non-const. 给出了相同的错误,我正在尝试从const转换为非const。 Doing a const_cast when I assign p does the trick, but since casting should be avoided, I was wondering if there's a better way to do this.
当我分配p时执行const_cast可以解决问题,但是由于应该避免强制转换,因此我想知道是否有更好的方法可以做到这一点。
Just consider this: 只要考虑一下:
Someone calls last()
on a const
node that is already the last node. 有人在已经是最后一个节点的
const
节点上调用last()
。 It returns itself, as a pointer to non- const
node, which then can be used to modify it. 它返回自身,作为指向非
const
节点的指针,然后可用于修改它。 This violates const correctness. 这违反了const正确性。
Either make the method non- const
and return the pointer to non- const
: 将该方法非
const
,并返回指向非const
:
LinkedList::LinkedListElement<T>*
LinkedList::LinkedListElement<T>::last ();
or make the method const
and return a pointer to const
: 或使该方法
const
,并返回一个指针const
:
const LinkedList::LinkedListElement<T>*
LinkedList::LinkedListElement<T>::last () const;
Sorry for misunderstanding you. 抱歉误会你。 Since the last() function may return this pointer and you want to modify it,it's better to define this function as non-const;
由于last()函数可能会返回此指针,并且您要对其进行修改,因此最好将此函数定义为非常量;
And what about make "const END element" maybe like stl? 而如何使“ const END element”可能像stl一样呢? Element is END if
(next==NULL)
and we will not use END for store value. 如果
(next==NULL)
元素为END,那么我们将不使用END作为存储值。
[LIST]->(END) // empty list
[LIST]->(value1)->(value2)->(value3)->...->(END) // list with values
After this change, the END will be const
all the time. 这一变化后,最终将是
const
所有的时间。
And the iteration while (next!=NULL)
will be less buggy. 而
while (next!=NULL)
迭代将减少错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.