在模板容器的const函数中修改成员变量时发生编译错误
Compiler error modifiying member variable in a const function of a template container
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
。可能是前者
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- C++预处理会生成变量成员、资源库和映射
- 局部堆栈变量成员的返回值优化
- Google Mock:在目标类的构造函数中实例化的模拟私有变量成员
- 使用指向结构变量成员的指针访问该结构的成员的地址
- 如果派生类仅包含自动变量成员,是否有必要具有虚拟驱动器
- 线程安全性和静态变量/成员功能
- "static const char array"可以在 C 语言上包含变量成员吗
- 仅用于内部目的的类的所有变量/成员的技术术语是什么
- 如何强制转换变量成员以将其作为函数的引用参数传递
- 类中未声明变量成员函数
- 在 main 中初始化类的 "static const" 类型变量成员的更好方法
- c++模板类静态const变量成员作为映射键给出未定义引用
- 在类中初始化结构变量成员会导致分割错误
- 在c++中建模变量成员类型
- 模板私有静态变量成员的未定义符号
- 不能访问公共静态变量成员
- 常量变量成员在C++有什么用?
- g++ 4.8.2坚持简单变量成员是数组