我有一个实现链表的类。该类有一个 find() 方法,该方法可以查找链表中存在的值。我有另一个方法 add() ,它添加一个节点,但仅当该节点中包含的值尚不存在于列表中时。
所以我想在 add() 函数中做的是使用我的 find 方法而不是测试现有值,因为这就像第二次实现它一样。我的问题是,如何从该类的另一个方法中调用 find 方法?
我尝试打电话 this.find(x)
但这给了我错误。
这是我的一些代码:
// main function
SLList<int>list;
list.add(20);
list.add(14);
// SLList.h (interface and implementation)
template<typename T>
bool SLList<T>::find(const T& val) const {
// finds value
}
template<typename T>
void SLList<T>::add(const T& x) {
bool found = this.find(x);
if (found) return false;
// goes on to add a node in the Singly Linked list (SLList)
}
所以就像我说的,我希望能够从该类中的另一个方法中调用 find 方法,并且我认为我所要做的就是引用调用对象,然后调用它的 find方法,但正如我所说,这给了我很多错误。
谁能帮我解决这个问题,谢谢!
最佳答案
只需调用find(x)
。不需要这个。另外,this
是指向当前对象的指针。所以你必须执行this->find(x)
。
关于C++ 从类内部调用类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5710698/