问题
I get an compile error here and I have no idea whats wrong with the code. I am using g++ 4.9.2.
#include<iostream>
#include<deque>
using std::string;
using std::deque;
class Dummy {
public:
virtual ~Dummy(){};
Dummy():ID_("00") {};
private:
const string ID_;
};
int main(){
{
deque <Dummy> waiter;
waiter.push_back(Dummy());
waiter.erase( waiter.begin() );
}
return 0;
}
Edit: I know that removing the const removes the compilation error, but I have no idea why. Anyway, I need this const.
回答1:
std::deque::erase expects the type of element should be MoveAssignable:
Type requirements
T must meet the requirements of MoveAssignable.
And class Dummy
has a const member const string ID_;
, which make it not assignable by default assignment operator.
You might make ID_
a non-const member, or provide your own assignment operator to make it assignable. e.g.
Dummy& operator=(const Dummy&) { /* do nothing */ }
LIVE
回答2:
you should remove the const
prefix, so that the string can be changed:
string ID_;
or else change it to a static variable and initialize it like this:
class Dummy {
public:
virtual ~Dummy(){};
Dummy() {};
private:
static const string ID_;
};
const string Dummy::ID_ = "00";
you can find more information here about const string initialisation.
来源:https://stackoverflow.com/questions/33888571/compile-error-with-stddequeerase-with-const-members-of-the-class