使用 VS 2008 时,目标环境是带有 ARM 处理器的 Windows CE,如果这有所不同的话。我知道我们使用的编译器也有点过时了......
我遇到的基本问题是,我正在尝试为我编写的 map 包装器创建自己的迭代器,并且重载 operator->() 给我带来了麻烦。这是给我带来问题的代码:
const pair<wstring, PropertyMap*>* ObjectMapIterator::operator->() const
{
return &*m_MapIter;
}
我知道通常返回一个 const 变量并没有什么意义,但我似乎无法弄清楚如何以一种让程序的其余部分在不这样做的情况下保持常量正确的方式.
我得到的错误是这样的:
error C2440: 'return' : cannot convert from 'const std::pair<_Ty1,_Ty2> *' to 'const std::pair<_Ty1,_Ty2> *'
此迭代器的 header 如下所示:
class ObjectMapIterator
{
public:
ObjectMapIterator(const ObjectMap& rObjectMap);
const ObjectMapIterator& operator++(int rhs);
std::pair<std::wstring, PropertyMap*> operator*() const;
const std::pair<std::wstring, PropertyMap*>* operator->() const;
bool isDone() const;
private:
const std::map<std::wstring, PropertyMap*>* m_pPropertyMaps;
std::map<std::wstring, PropertyMap*>::const_iterator m_MapIter;
};
如您所见,m_MapIter 和重载运算符的返回值是相同的...我从项目的这一部分的 .h 和 .cpp 文件中取出所有 const 语句,并重新编译同样的错误,所以我认为这不是问题。
如果我改为这样做,程序将编译:
const pair<wstring, PropertyMap*>* ObjectMapIterator::operator->() const
{
const pair<wstring, PropertyMap*>* returnVal = new pair<wstring, PropertyMap*>(*m_MapIter);
return returnVal;
}
我知道这样做会导致内存泄漏,我没有将它放入智能指针只是为了节省发布空间。
这是整个 .cpp 文件,以防您发现相关内容:
#include "stdafx.h"
#include "ObjectMap.h"
using namespace std;
ObjectMapIterator::ObjectMapIterator(const ObjectMap& rObjectMap)
:m_pPropertyMaps(&(rObjectMap.m_PropertyMaps)),
m_MapIter(m_pPropertyMaps->begin())
{}
const ObjectMapIterator& ObjectMapIterator::operator++(int rhs)
{
if(m_MapIter != m_pPropertyMaps->end())
{
m_MapIter++;
return *this;
}
else
{
return *this;
}
}
pair<wstring, PropertyMap*> ObjectMapIterator::operator*() const
{
return *m_MapIter;
}
const pair<wstring, PropertyMap*>* ObjectMapIterator::operator->() const
{
return &*m_MapIter;
}
bool ObjectMapIterator::isDone() const
{
return m_MapIter == m_pPropertyMaps->end();
}
ObjectMapIterator 定义在 ObjectMap.h 文件中。所以我没有忘记包含 ObjectMapIterator。
我已经为这个问题挠头太久了。如果您有任何发现,请告诉我。谢谢!
最佳答案
std::map::const_iterator
返回一个临时值,而不是一个引用,因此您正在尝试获取该临时值的地址并将其返回。
为什么不简单地按值返回对
?
std::pair<std::wstring, PropertyMap*>* ObjectMapIterator::operator->() const
{
return *m_MapIter;
}
实际上,如果您的运算符将返回 std::map::const_iterator::pointer
,如
std::map::const_iterator::operator->()
确实如此,一切都会好起来的:
std::map<std::wstring, PropertyMap*>::const_iterator::pointer operator->() const
{
return &*m_MapIter;
}
此外,就 std::map::const_iterator::operator->()
返回的值而言,它是实现定义的,使用它可能会更好
auto operator->() const -> decltype(m_MapIter.operator->())
{
return (m_MapIter.operator->());
}
关于c++ - 取消引用迭代器导致 'can not convert' 错误,但它似乎不应该,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9811813/