c++从类内调用类方法

linked list - C++ call class method from within class

本文关键字:调用 类方法 c++      更新时间:2023-10-16

我有一个实现链表的类。这个类有一个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)

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

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

另一方面,您的函数SLList<T>::add(const T& x)应该返回bool(而不是void)。