在模板容器的const函数中修改成员变量时发生编译错误

Compiler error modifiying member variable in a const function of a template container

本文关键字:变量 成员 错误 编译 修改 函数 const      更新时间:2023-10-16
template <template <class, class> class ContainerType>
class Movie {
public:
    typedef ContainerType<Actor*, std::allocator<Actor*>> Container;
    bool removeActor(int id) const {
        const Actor* factor = findActor(id);
        typename Container::const_iterator it;
        if (factor == 0) {
            return 0;
        }
        it = std::find_if(actors.begin(), actors.end(), removeActor2(id));
        **actors.erase(it);
        **delete factor;
        return 1;
    }
private:
    std::string _title;
    std::string _director;
    std::string _genre;
    int _rating;
    Container actors;
};
class removeActor2 {
public:
    removeActor2(int id) : _id(id) {}
    const Actor* operator()(Actor* act) {
        if (act->getId() == _id) {
            return act;
        }
        return 0;
    }
private:
    int _id;
};

错误:

||=== Build: Debug in hw2 (compiler: GNU GCC Compiler) ===|
In instantiation of 'bool summer2014::Movie<ContainerType>::removeActor(int) const [with ContainerType = std::list]':|
|error: no matching function for call to 'std::list<summer2014::Actor*, std::allocator<summer2014::Actor*> >::erase(std::list<summer2014::Actor*, std::allocator<summer2014::Actor*> >::const_iterator&) const'|
 candidates are:|
|108|note: std::list<_Tp, _Alloc>::iterator std::list<_Tp, _Alloc>::erase(std::list<_Tp, _Alloc>::iterator) [with _Tp = summer2014::Actor*; _Alloc = std::allocator<summer2014::Actor*>; std::list<_Tp, _Alloc>::iterator = std::_List_iterator<summer2014::Actor*>]|
|108|note:   no known conversion for argument 1 from 'std::list<summer2014::Actor*, std::allocator<summer2014::Actor*> >::const_iterator {aka std::_List_const_iterator<summer2014::Actor*>}' to 'std::list<summer2014::Actor*, std::allocator<summer2014::Actor*> >::iterator {aka std::_List_iterator<summer2014::Actor*>}'|
note: std::list<_Tp, _Alloc>::iterator std::list<_Tp, _Alloc>::erase(std::list<_Tp, _Alloc>::iterator, std::list<_Tp, _Alloc>::iterator) [with _Tp = summer2014::Actor*; _Alloc = std::allocator<summer2014::Actor*>; std::list<_Tp, _Alloc>::iterator = std::_List_iterator<summer2014::Actor*>]|
|1193|note:   candidate expects 2 arguments, 1 provided|

您正在尝试修改const成员中的成员。这行不通。使removeActor()const或将actors声明为mutable。可能是前者