C++ 함수를 const로 바꾼 경우 C2440 컴파일 오류가 발생한다면?
예를 들어 다음의 소스 코드에서,
#include "stdafx.h"
#include <map>
using namespace std;
class My
{
public:
auto test() -> int;
private:
map<int, int> _map;
};
auto My::test() -> int
{
map<int, int>::iterator it = _map.find(5);
return 5;
}
int main()
{
return 0;
}
test 함수를 const 메서드로 바꾸면,
class My
{
public:
auto test() const -> int;
private:
map<int, int> _map;
};
auto My::test() const -> int
{
map<int, int>::iterator it = _map.find(5);
return 5;
}
다음과 같은 오류가 발생합니다.
Error C2440 'initializing': cannot convert from 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>' to 'std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>'
오류 코드의 복잡함에 당황하지 마시고 자세히 보면 답이 나옵니다.
cannot convert from
'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>'
to
'std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>'
똑똑한 stl은 const 문맥 내에서 수행될 const 함수를 미리 마련해 두었고, 따라서 위의 오류 메시지대로 다음과 같이 소스 코드를 바꿔주면 됩니다.
auto My::test() const -> int
{
map<int, int>::const_iterator it = _map.find(5);
return 5;
}
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]