以下代码无法编译(Ideone 链接:https://ideone.com/DKI9Fm)。为什么?:
编辑:根据documentation std::map
的 const Key&
类型被 std::map::find
接受。所以将 const int*
传递给 find()
应该没问题。
#include <iostream>
#include <map>
using namespace std;
class ConstDemo
{
std::map<int*, int> m_Map;
public:
ConstDemo(int count, int* pArray)
{
for(int i=0; i < count; ++i)
{
m_Map.insert(std::make_pair(&(pArray[i]),0));
}
}
bool Find(const int* i) const
{
// DOESN"T COMPILE!
return (m_Map.find(i) != m_Map.end());
}
};
int main() {
int a[10];
ConstDemo cd(10, a);
if(cd.Find(&a[5]))
cout << "Found!" << std::endl;
return 0;
}
最佳答案
const int*
和 int* const
不一样。尝试将其更改为 int* const
:
bool Find(int* const i) const
这是因为您的 key_type
是int*
(std::map<int*, int> m_Map;
)。和 m_Map.find
期待一个 const key_type
作为参数,即 int* const
在你的情况下。但是你传递的是 const int**
.
如果你传递一个 int*
至 m_Map.find
, 也可以,因为它可以转换 int*
至 int* const
, 但它不能转换 int*
至 const int*
.
而且,在下一行 int main
的末尾缺少一个分号:
ConstDemo cd(10, a)
现在,在 Ideone 上查看.
编辑:
问题修改后
As per documentation of
std::map
,const Key&
type is accepted bystd::map::find
. So passingconst int*
tofind()
should be okay.
const Key&
是常数 Key
,所以在你的情况下,你需要传递一个常量
int*
现在。但是const int*
没有定义常量 int*
, 它仅仅定义了一个指向 const int
的指针. int* const
定义一个常量 int*
,所以这就是为什么如果您通过 const int*
会出错的原因.
关于c++ - 为什么这一行不编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47344003/