c++ - 为什么这一行不编译?

标签 c++ stl

以下代码无法编译(Ideone 链接:https://ideone.com/DKI9Fm)。为什么?:

编辑:根据documentation std::mapconst 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_typeint* (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 by std::map::find. So passing const int* to find() 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/

相关文章:

c++ - 指向类成员函数的函数指针问题

c++ - 使用继承构造函数时 VS2015 内部编译器错误

c++ - 如何将 std::set_intersection 用于 2 个不同但相关的类型并输出到另一种类型

c++ - 是否有任何支持以下操作的boost/STL容器?

c++ - STL::find_if 与用户搜索

c++ 使用 "*"运算符没有运算符匹配这些操作数

c++ - 如何使用命名空间和类?

c++ - 如何在带有 STL vector 的 C++ 中使用类似 matlab 的运算符

c++ - C++二进制文件数据解析 : and the right STL for it?

c++ - 为什么要使用 std::forward?