Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建指向“的指针”;这";对象 我在项目中遇到一些问题,试图创建一个指向“这个”的指针,其中“这个”是C++中的第一个链接列表。第一个对象包含数据,第二个对象包含…等等,直到this->m_next为NULL_C++_Constants - Fatal编程技术网 m_next为NULL,c++,constants,C++,Constants" /> m_next为NULL,c++,constants,C++,Constants" />

创建指向“的指针”;这";对象 我在项目中遇到一些问题,试图创建一个指向“这个”的指针,其中“这个”是C++中的第一个链接列表。第一个对象包含数据,第二个对象包含…等等,直到this->m_next为NULL

创建指向“的指针”;这";对象 我在项目中遇到一些问题,试图创建一个指向“这个”的指针,其中“这个”是C++中的第一个链接列表。第一个对象包含数据,第二个对象包含…等等,直到this->m_next为NULL,c++,constants,C++,Constants,编译器正在向我吐露这句话: linkedlist.hpp:55:22:错误:从–const linkedlist*const–到–linkedlist*的转换无效[-fpermissive] 我做错了什么 template <typename T> int LinkedList<T>::size() const { int count = 0; LinkedList* list = this; // this line is what the compiler

编译器正在向我吐露这句话:

linkedlist.hpp:55:22:错误:从–const linkedlist*const–到–linkedlist*的转换无效[-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;
}
模板
int LinkedList::size()常量
{
整数计数=0;
LinkedList*list=this;//这一行是编译器所抱怨的
//如果列表中有其他对象,则添加到计数器
while(list->m_next!=NULL)
{
计数++;
列表=列表->m_下一步;
}
返回计数;
}
尝试更改

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

LinkedList const*list=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>
const LinkedList*list=this;//因为“this”是常量,所以列表也应该是常量
//               ^
//               |
//还添加了您需要的模板参数,因为“this”
//是一个链接列表
更改

LinkedList* list = this; 

const LinkedList*list=this;
^^^^^           ^^^ 
由于您的函数定义为
const
,因此
指针自动
const LinkedList*

因此,无法将
常量
指针指定给非
常量
指针
,以解释错误


如果您尝试使用非
int
参数,则缺少的
可能会给您带来错误。

因此,我有一个简短的问题。当常量在前面时,您是否正在创建指向常量对象的指针?或者你正在制作一个指向一个对象的常量指针?当
常量像这样在前面时,它是一个“指向
常量链接列表的指针”(指向常量对象的指针),当它在后面时,它是一个常量指针(也就是说它不能被重新指向)@MasterGberry:是的,当
常量
*
之后时,然后它是一个“指向(任何类型的对象)”的常量指针。还要注意,例如,
const int*
int const*
相同(请注意,在这两种情况下,
const
位于
*
之前,因此它们都是“指向常量整数的指针”)。但是,
int*const
是一个“指向整数的常量指针”(因为它在
*
后面有
const
)。
LinkedList* list = this; 
const LinkedList<T>* list = this; 
^^^^^           ^^^