C++ error C2662: “LinkNode<T> *List<T>::Locate(int)”: 不能将“this”指针从“const List<int>”转换为“List<int> &”
2017-09-24 20:52
666 查看
错误 1 error C2662: “LinkNode<T> *List<T>::Locate(int)”: 不能将“this”指针从“const List<int>”转换为“List<int> &” e:\datastructure\cap_1\cap_1\singlelist.cpp 123 1 Cap_1
今天在写数据结构的单链表时遇到此错误,在网上查了相关的错误资料,并修改过来,次分享!错误根本原因是const修饰的问题,下面结合代码分析具体原因:
template<class T>
LinkNode<T> * List<T>::Locate(int i) {
//定位函数 返回表中第i个节点的地址 如果i < 0 或者i 超过链表长度则返回NULL
if (i < 0) {
return NULL;
}
LinkNode<T> * current = first;
int m = 0;
while (current != NULL && m < i) {
current = current->link;
m++;
}
return current;
}
template<class T>
bool List<T>::getData(int i, T & x) const{
//取出链表中第i个节点的data
if (i <= 0) {
return NULL; //数据非法返回false
}
LinkNode<T> * current = Locate(i); //借助定位函数直接定位到相应的节点
if (NULL == current) {
return false; //i超过单链表的长度返回false
}
else {
x = current->data;
return true;
}
}
这是这个单链表类中的定位函数和数据提取函数,开始的时候,我把数据提取函数定义为const修饰(然而定位函数没有),这个时候在用提取数据函数调用定位函数的时候报出上面的error,下面是网上的原因:
对象引用前加const报错:不能将“this”指针从“const a”转换为“a &”
const a &aa相当于一个const对象,由于const对象在调用成员函数的时候,会将this指针强行转换为const this,所以它将无法找到相应的const show()函数,并且编译器也无法将一个const的对象转化为一个普通对象来调用这个普通的show()方法,所以就会产生如题的编译错误。
结合自己的代码分析了一下这个原因,说白了就是,一个函数定义成了const修饰(即不能通过此成员函数修改成员变量),而如果此函数要嵌套调用其它成员函数,那么这个函数也必须是const修饰的,否则就会报error,其实也好理解,你用一不能修改成员变量的函数来调用可以修改成员变量的函数这本身就是矛盾的,所以C++中不允许这样做。
而网上的这个分析,属于分析道了本质,是一个const对象调用了非const函数,道理上是一样的,希望大家可以从中收获!
下面是改正后的代码(把被调用的函数用const修饰,使之统一)
相关链接 :http://blog.csdn.net/bagboy_taobao_com/article/details/5709414
相关文章推荐
- LNK2019: 无法解析的外部符号 "public: void __thiscall List<int>::add(int const &)" (?add@?$List@H@@QAEXABH@Z),
- 不能将参数 1 从“int &(__thiscall RBTree<T>::* )(RBTreeNode<T> *)”转换为“int &(__cdecl *)(RBTreeNode<T> *)”
- 不能将参数 1 从“int”转换为“std::_Vector_const_iterator<_Myvec>”(VS2010 )
- 不能将this指针从“const type" 转换为"type &"
- 基类代码error C2662: 不能将“this”指针从“const Node_align”转换为“Node_align &”解决方案
- List<?>不能直接被类型转换
- list<string>转换成list<int>类型
- 指向list 的指针 list<int> *pmylist = new list<int> [2];
- error C2662: 不能将“this”指针从“const Node_align”转换为“Node_align &”解决方案
- DataTable转换为List<Model>的通用类
- json转换成list<T>
- 使用了<input type="submit" value="Submit" onclick="this.disabled=true" />不能提交
- DataTable转换成List<T>
- int、string、vector<int>的转换
- 将DataTable转换成泛型集合IList<>
- Java 中的 int 与 Integer 用于 List<Integer> 时,以及通过打印变量检测程序运行和函数调用次数计数
- 将DataTable转换成List<T>泛型集合助手类
- 对C++中类型显示转换操作符const_cast<类型>(变量)的认识
- java 将jso 格式的字符串转换为List<Map<String,String>>
- error C2664: “BOOL CDC::TextOutW(int,int,const CString &)”: 不能将参数 3 从“const char [18]”转换为“const CString &”