我遇到了一个我不理解的编译问题,我在下面对其进行了简化解释.
基本上,它涉及两个不同的getter(一个const和一个const),它们返回一个容器(在这个例子中是一个映射),它们分别是const,非const value_type.
令我困惑的是,在下面的示例中,编译器似乎无法在非const对象上使用const getter:
#include "stdafx.h"
#include <utility>
#include <map>
class TestObject
{
public:
TestObject() {}
virtual ~TestObject() {}
};
typedef std::pair<const TestObject*, const TestObject*> ConstTestObjectPair;
typedef std::pair<TestObject*, TestObject*> TestObjectPair;
class Test
{
TestObject* m_pObject;
public:
Test() {m_pObject = new TestObject();}
virtual ~Test() {delete m_pObject;}
std::map<unsigned, ConstTestObjectPair> GetObject() const
{
std::map<unsigned, ConstTestObjectPair> map;
map.insert(std::make_pair(0, std::make_pair(m_pObject, m_pObject)));
return map;
}
std::map<unsigned, TestObjectPair> GetObject()
{
std::map<unsigned, TestObjectPair> map;
map.insert(std::make_pair(0, std::make_pair(m_pObject, m_pObject)));
return map;
}
};
int _tmain(int argc, _TCHAR* argv[])
{ …Run Code Online (Sandbox Code Playgroud)