2

我有一个实现链表的类。该类有一个 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 方法,但是正如我所说,这给了我一堆错误。

任何人都可以帮助我如何称呼这个,谢谢!

4

2 回答 2

4

只要打电话find(x)。不需要这个。另外,this是指向当前对象的指针。所以你必须这样做this->find(x)

于 2011-04-19T01:50:11.567 回答
1

this是一个指针,如果你想使用它应该是以下两种方式之一:

this->find(x);
(*this).find(x);
find(x);

附带说明,您的函数SLList<T>::add(const T& x)应该返回bool(不是void)。

于 2011-04-19T02:00:51.433 回答