我想知道C++中是否有一种方法可以知道所谓的函数?类似于Java或JavaScript中的this关键字。
例如,我有一个称为插入的函数,该函数将一个项目插入到链表中,我希望调用该函数的链表插入该函数以调用其他两个函数。我该怎么办?
我现在有这个,这有效吗?
bool linked_list::insert( int i )
{
bool inserted = false;
if( this.is_present(i) ) /* function is_present is defined earlier checks if an int is already in the linked-list. */
{
inserted = true // already inside the linked-list
}
else
{
this.Put( 0, i ); /* function Put is defined earlier and puts an int in a linked-list at a given position (first param.). */
inserted = true; // it was put it.
}
return inserted;
}
最佳答案
对于historical reasons,this
是一个指针。使用->
而不是.
。
bool linked_list::insert(int i) {
bool inserted = false;
if(this->is_present(i)) {
inserted = true; // fixed syntax error while I was at it.
} else {
this->put(0, i); // fixed inconsistent naming while I was at it.
inserted = true;
}
return inserted;
}
通常,根本不需要使用
this->
;您可以只做if(is_present(i))
。