【问题标题】:Compiler error modifiying member variable in a const function of a template container编译器错误修改模板容器的 const 函数中的成员变量
【发布时间】:2014-08-23 20:18:11
【问题描述】:
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
  • @T.C. constantly 可能会删除东西
  • ...你的问题是?

标签: c++ list c++11 vector stl


【解决方案1】:

您正在尝试修改const 成员中的成员。那是行不通的。要么将removeActor() 设为非const,要么将actors 声明为mutable。应该是前者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多