【问题标题】:Why vector::erase can't work on class element with const为什么 vector::erase 不能使用 const 处理类元素
【发布时间】:2019-06-26 16:50:45
【问题描述】:

我试图擦除存储包含 const 成员的类的向量的元素,但失败并出现错误。

当我删除常量修饰符时,程序正常编译。

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'

【问题讨论】:

    标签: c++ stdvector


    【解决方案1】:

    对向量的某些操作要求元素可以复制或移动分配 [ref]。

    在这种情况下,您会看到 .erase 函数的实现无法编译,因为它需要知道如何在容器中随机播放元素 [ref](即使您的特定示例只会导致在一个空向量中)。

    当您创建成员 const 时,您会阻止它。

    你不能拥有那个const

    【讨论】:

    • Turbo C++编译会编译失败。
    • @SombreroChicken 这没什么好说的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 2023-03-26
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多