std :: list push_back()和pop_front()给出常量错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了std :: list push_back()和pop_front()给出常量错误相关的知识,希望对你有一定的参考价值。
我正在从事一个编码项目,遇到了一些麻烦。当我尝试制作时,出现以下错误:
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
答案
您正在尝试在this->pop_back()
方法中分别调用this->push_back()
和const
。从const
Mean::Calculate()
中删除and the code will compile限定词。
以上是关于std :: list push_back()和pop_front()给出常量错误的主要内容,如果未能解决你的问题,请参考以下文章
C++ list使用remove_if 移除所有小于n的数字
没有匹配函数调用‘std::vector::push_back(std::string&)’