std :: list push_back()和pop_front()给出const错误

时间:2019-11-27 20:23:21

标签: c++ c++11

我正在从事一个编码项目,遇到了一些麻烦。尝试制作时,出现以下错误:

src/mean.cc:26:12: error: passing ‘const csce240::Mean’ as ‘this’ argument discards qualifiers [-fpermissive]
   pop_back();
            ^
In file included from /usr/include/c++/7/list:63:0,
                 from inc/mean.h:9,
                 from src/mean.cc:2:
/usr/include/c++/7/bits/stl_list.h:1152:7: note:   in call to ‘void std::__cxx11::list<_Tp, _Alloc>::pop_back() [with _Tp = double; _Alloc = std::allocator<double>]’
       pop_back() _GLIBCXX_NOEXCEPT
       ^~~~~~~~
src/mean.cc:33:29: error: passing ‘const csce240::Mean’ as ‘this’ argument discards qualifiers [-fpermissive]
   push_front(tempList.back());
                             ^
In file included from /usr/include/c++/7/list:63:0,
                 from inc/mean.h:9,
                 from src/mean.cc:2:
/usr/include/c++/7/bits/stl_list.h:1067:7: note:   in call to ‘void std::__cxx11::list<_Tp, _Alloc>::push_front(const value_type&) [with _Tp = double; _Alloc = std::allocator<double>; std::__cxx11::list<_Tp, _Alloc>::value_type = double]’
       push_front(const value_type& __x)
       ^~~~~~~~~~

我能找到的最接近的解决方案是将const添加到函数定义的末尾,但是该定义已经开始。这是.h和.cc文件:

// Copyright 2019 Ian McDowell
#ifndef _CSCE240_HW_HW6_INC_MEAN_H //NOLINT
#define _CSCE240_HW_HW6_INC_MEAN_H //NOLINT

/* This class inherits from the Statistic class such that it may be used
 * polymorphically.
 */
#include <statistic.h>
#include <list>

namespace csce240 {

class Mean : public std::list<double>, public Statistic {
 public:

  /* Stores data (datum) such than an average may be calculated.
   * - NOTE: You do not necessarily need to store each datum.
   */
  void Collect(double datum);

  /* Returns the mean of the data (datum) from the Collect method.
   */
  double Calculate() const;
};

} // namespace csce240

#endif //NOLINT

---------------------- Mean.cc ---------------------- -------

// Copyright 2019 Ian McDowell
#include <mean.h>
using std::list;

namespace csce240 {

void Mean::Collect(double datum) {
    push_front(datum);
}

double Mean::Calculate() const {
    list<double> tempList;
    int i = 0;
    double temp;
    double avg = 0;

    while (!empty()) {
        temp = back();
        avg += temp;
        tempList.push_front(temp);
        pop_back();
        ++i;
    }

    avg = avg / i;

    while(!tempList.empty()) {
        push_front(tempList.back());
        tempList.pop_back();
    }

    return avg;
}


} // namespace csce240

1 个答案:

答案 0 :(得分:5)

您正试图在this->pop_back()方法中分别调用this->push_back()const

const and the code will compile中删除Mean::Calculate()限定词。