我试图删除存储包含 const 成员的类的 vector 的元素,但我失败了并出现错误。
当我删除常量修饰符时,程序可以正常编译。
class C
{
public:
const int i;
C(int i = 1):i(i){};
};
int main()
{
vector<C> v;
C c;
v.push_back(c);
v.erase(v.begin());
return 0;
}
error C2280: 'C &C::operator =(const C &)': attempting to reference a deleted function
m.cpp(151): note: compiler has generated 'C::operator =' here
m.cpp(151): note: 'C &C::operator =(const C &)': function was implicitly deleted because 'C' has a data member 'C::i' of const-qualified non-class type
m.cpp(146): note: see declaration of 'C::i'
最佳答案
vector 上的某些操作要求元素可复制或移动分配[ ref ].
在这种情况下,您会看到 .erase
函数的实现无法编译,因为它需要知道如何在容器中随机排列元素 [ ref ] (即使您的特定示例只会导致空 vector )。
当你让一个成员const
时,你就阻止了它。
你不能拥有那个 const
。
关于c++ - 为什么 vector::erase 不能在带有 const 的类元素上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56777658/