0

我似乎在尝试创建指向“this”的指针的项目中遇到问题,其中“this”是 C++ 列表中的第一个 LinkedList。第一个对象中包含数据,第二个对象中有数据……等等,this->m_next直到NULL

编译器向我吐出这个:

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;
}
4

3 回答 3

5

成员函数标记为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>
于 2013-02-22T01:52:29.470 回答
1

尝试改变

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

LinkedList<T> const * list = this; 
          ^^^ ^^^^^   
于 2013-02-22T01:51:52.810 回答
1

改变

LinkedList* list = this; 

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

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

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

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

于 2013-02-22T01:52:41.553 回答