C++错误:将 const 作为参数传递'this'
C++ error: passing const as 'this' argument
这是一个链表,我试图过载==,它给了我错误:错误:传递'const Linked_List作为'ItemType Linked_List::Element(int) [with ItemType = int]'的' This '参数丢弃限定词。
我必须检查两个链表是否有相同数量的元素,以及每个元素是否相等。
错误指向==的实现部分以下是节选:ps: element(i)返回链表
第i位的值template <typename ItemType>
bool Linked_List <ItemType>::operator == (const Linked_List &eq)const {
if (eq.Items != Items){
return false;
}
if (eq.Items == 0){
return true;
}
for (int i = 0; i < eq.Items; i++){
if (eq.Element(i) != Element(i)){ //error points here
return false;
}
}
return true;
}
这是我剩下的可能相关的代码。我没有发布我所有的代码,因为一切都很好,包括element(),只有重载不会工作。
//.h
template <typename ItemType>
class Node
{
public:
ItemType Data;
Node <ItemType> *next;
};
template <typename ItemType>
class Linked_List
{
public:
Node <ItemType> *start;
int Items;
Linked_List();
ItemType Element(int num);
bool operator == (const Linked_List &eq)const;
}
.
.//cpp
#include "Linked_List.h"
template <typename ItemType>
Linked_List <ItemType>::Linked_List(){
start = NULL;
Items = 0;
}
template <typename ItemType>
ItemType Linked_List <ItemType>::Element(int num){
ItemType result = 0;
if (start == NULL){
return result;
}
Node <ItemType> *nnode;
nnode = start;
int current_position = 0;
while (current_position < num){
current_position++;
nnode = nnode -> next;
}
result = nnode -> Data;
nnode = NULL;
delete nnode;
return result;
}
template <typename ItemType>
bool Linked_List <ItemType>::operator == (const Linked_List &eq)const {
if (eq.Items != Items){
return false;
}
if (eq.Items == 0){
return true;
}
for (int i = 0; i < eq.Items; i++){
if (eq.Element(i) != Element(i)){ //error
return false;
}
}
return true;
}
int main(){
Linked_List <int> test8;
Linked_List <int> test7;
cout << (test8 == test7) << endl;
}
声明为const
的方法只能调用其他const
方法。它们不能是非const方法。在您的案例方法中,operator ==
被声明为const
。从operator ==
内部,您正在尝试调用方法Element
,这是非const。这是你的错误。
而且,两个Element
调用
if (eq.Element(i) != Element(i))
无效。第一个调用是无效的,因为eq
是const
引用,这意味着您不能通过它调用任何非const方法。由于上述原因,第二个调用无效。
要么将Element
方法声明为const
,要么提供Element
的第二个const
版本,除了非const版本。我看到元素通过值返回结果,这意味着您可以简单地将其声明为const
。
相关文章:
- 错误:将 x 作为 x 的参数传递'this'丢弃限定符
- 错误:将“const sdf”作为“this”参数传递会丢弃限定符 [-fpermissive]
- 错误:将'xxx'作为'xxx'丢弃限定符的参数传递'this' [-允许]
- std::remove_if 将“const type”作为“this”参数传递会丢弃 Linux 上的限定符
- 将'const'作为参数传递'this'时出错
- (C++)将"this"作为默认参数传递给静态方法
- 将“const CMyclass”作为..的“this”参数传递.丢弃限定符 [-允许]
- 错误:将“const Cell”作为“void Cell::p rintcell()”的“this”参数传递丢弃限定符[
- 如果参数采用引用,在函数参数中传递 *this 会导致内存泄漏
- 错误:将'const …'作为'…'的参数传递'this'在调用方法中丢弃限定符
- 将“const”作为“const double”的“this”参数传递时出错,将丢弃限定符
- 错误:将"const Complex"作为'....'丢弃限定符的"this"参数传递
- 是否允许将 *this 作为接受引用(&)的函数的参数传递?
- 将全局常量作为"this"参数传递会丢弃限定符
- 错误:将'const Tarih'作为'void(int)' 'this'参数传递丢弃限定符|
- 错误:将"xxx"作为"this"参数传递会丢弃限定符
- 将"this"作为参数传递时从 const "No known conversion"
- C++错误:将 xxx 作为 xxx 的参数传递'this'丢弃限定符
- C++错误:将 const 作为参数传递'this'
- 修复错误:将'const foo'作为'const size_t foo::method()'的参数传递'this'