创建指向对象的指针"this"

Create pointer to "this" object

本文关键字:指针 this 对象 创建      更新时间:2023-10-16

我在一个项目中似乎遇到了问题,试图创建一个指向"this"的指针,其中"this"是C++中列表中的第一个LinkedList。第一个对象有数据,第二个有。。。直到CCD_ 1是CCD_ 2

编译器向我吐出了这样的话:

linkedlist.hpp:55:22: error: invalid conversion from âconst LinkedList<int>* constâ to âLinkedList<int>*â [-fpermissive]

我做错了什么?

template <typename T>  
int LinkedList<T>::size() const
{
  int count = 0;
  LinkedList* list = this; // this line is what the compiler is complaining about
  //adds to the counter if there is another object in list
  while(list->m_next != NULL)
  {
    count++;
    list = list->m_next;
  }
  return count;
}

成员函数标记为const。这意味着this也是const。你需要做:

const LinkedList<T>* list = this; // since "this" is const, list should be too
//               ^
//               |
//               Also added the template parameter, which you need, since "this"
//               is a LinkedList<T>

更改

LinkedList* list = this; 

const LinkedList<T>* list = this; 
^^^^^           ^^^ 

由于函数定义为const,因此this指针自动为类型的const LinkedList<T>*

因此,您不能将this->m_next0指针分配给非const指针,从而解释错误。

如果您尝试非int参数,丢失的<T>可能会给您带来错误。

尝试更改

LinkedList* list = this; // this line is what the compiler is complaining about

LinkedList<T> const * list = this; 
          ^^^ ^^^^^