我找不到比直接粘贴在这里更简单的方法来解释我的问题(虽然是简化版本)。我有一个带有必要赋值运算符、默认构造函数和common
复制构造函数的模板类。当我尝试在我的代码中使用这个类时,我收到如下错误:
#include<map>
#include<vector>
template<class T>
class BufferContainer
{
public:
BufferContainer& operator=(BufferContainer& other)
{
buffer = other.get();
return *this;
}
BufferContainer( const BufferContainer& other ) :
buffer( other.get() )
{
}
BufferContainer(){
}
std::vector<T>& get() {
return buffer;
}
void add(T value) {
buffer.push_back(value);
}
std::vector<T> buffer;
};
int main()
{
std::map<int, BufferContainer<int> > myMap;
myMap[1].add(1);
return 1;
}
错误是:
Practice $ g++ template.cpp
template.cpp: In instantiation of ‘BufferContainer<T>::BufferContainer(const BufferContainer<T>&) [with T = int; BufferContainer<T> = BufferContainer<int>]’:
/usr/include/c++/4.7/bits/stl_pair.h:105:31: required from ‘std::pair<_T1, _T2>::pair(const _T1&, const _T2&) [with _T1 = const int; _T2 = BufferContainer<int>]’
/usr/include/c++/4.7/bits/stl_map.h:458:11: required from ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = int; _Tp = BufferContainer<int>; _Compare = std::less<int>; _Alloc = std::allocator<std::pair<const int, BufferContainer<int> > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = BufferContainer<int>; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]’
template.cpp:38:9: required from here
template.cpp:16:26: error: passing ‘const BufferContainer<int>’ as ‘this’ argument of ‘std::vector<T>& BufferContainer<T>::get() [with T = int]’ discards qualifiers [-fpermissive]
如果您帮助我解决此问题的方法,我将不胜感激,更重要的是,告诉我为什么会出现此错误。谢谢