编译器"error: passing ‘const something’ as ‘this’ argument discards qualifiers"

compiler "error: passing ‘const something’ as ‘this’ argument discards qualifiers"

本文关键字:this as discards qualifiers argument const error passing 编译器 something      更新时间:2023-10-16

我正在使用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; }
  1. 如前所述,一种选择是使length符合常量。
  2. 另一种选择是在output函数中使用const_cast。
sortedList<int>& ref = const_cast <sortedList<int>&>(list);
cout << "length" << ref.length() << endl;

(2) 当我们没有奢侈地更新 (1) 中提到的类方法时特别有用。