编译器"error: passing ‘const something’ as ‘this’ argument discards qualifiers"
compiler "error: passing ‘const something’ as ‘this’ argument discards qualifiers"
我正在使用C++中的模板制作自定义列表,并得到一些编译错误。
代码的长度非常大,所以这里是一小段代码,错误来自哪里。编译错误如下。您可以编译自己的系统以查看相同的错误。
#include <iostream>
using namespace std;
template <class T>
class sortedList
{
int m_count;
public:
sortedList(){m_count = 0;}
int length(){ return m_count; }
};
void output(const sortedList<int>& list)
{
cout << "length" << list.length() << endl;
return;
}
int main() {
// your code goes here
sortedList <int> list1;
output(list1);
return 0;
}
我收到编译错误:
prog.cpp: In function ‘void output(const sortedList<int>&)’:
prog.cpp:17:35: error: passing ‘const sortedList<int>’ as ‘this’ argument discards qualifiers [-fpermissive]
cout << "length" << list.length() << endl;
^
prog.cpp:10:6: note: in call to ‘int sortedList<T>::length() [with T = int]’
int length(){ return m_count; }
您必须length
才能获得 const 资格:
int length(){ return m_count; }
→
int length() const { return m_count; }
- 如前所述,一种选择是使
length
符合常量。 - 另一种选择是在
output
函数中使用const_cast。
sortedList<int>& ref = const_cast <sortedList<int>&>(list); cout << "length" << ref.length() << endl;
(2) 当我们没有奢侈地更新 (1) 中提到的类方法时特别有用。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么使用 "this" 指针调用派生成员函数?
- C++错误:"error: int aaa::bbb is protected within this context"
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 关于C++中具有多重继承"this"指针的说明
- 在noexcept 规范中是否允许使用"this"?
- 如何修复"error: ‘_1’ was not declared in this scope"?
- 为什么我会" void value not ignored as it ought to be"?
- C++调用具有 *this 属性的单个帮助程序函数
- Doees the 'this' 指针参与虚函数的多态行为
- 在 c++ 中正确定义"this"关键字?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- QObject::连接无法将信号连接到*this*对象的插槽
- "passing const XXX as this disregards qualifiers"解释 ?
- 方法定义中的错误"passing const List<int> as this argument discards qualifiers"
- 编译器"error: passing ‘const something’ as ‘this’ argument discards qualifiers"
- "error: C2275: 'QMouseEvent' : illegal use of this type as an expression"
- 简单的模板化函数,用于转换 std::vectors - "illegal use of this type as an expression"