为什么这行不能编译?

时间:2017-11-17 05:43:12

标签: c++ stl

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

编辑:根据std::map的{​​{3}},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;
}

2 个答案:

答案 0 :(得分:2)

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*

而且,在以下行main的末尾缺少分号:

ConstDemo cd(10, a)

现在,请在Ideone上查看。

修改

在您的问题中进行编辑后

  

根据std::map的文档,const Key&接受std::map::find类型。因此,将const int*传递给find()应该没问题。

const Key&是一个常量Key,所以在你的情况下,你需要传递一个常量 int*现在。但是const int*没有定义常量int*,它只定义了指向const int的指针。 int* const定义了一个常量int*,这就是为什么如果您通过const int*会给出错误的原因。

答案 1 :(得分:0)

简短回答:

使用

bool Find(int* i) const { ... }

答案很长:

{C} 11之前std::map::find的声明:

iterator find( const Key& key );
const_iterator find( const Key& key ) const;

参数类型为const Key&,而不是KeyKey&

在您的情况下,Keyint*,而不是cons int*

如果我们在声明中替换Key,它们看起来像:

iterator find( int * const & key );  // Not "const int*&"
                                     // That's unforunate part
const_iterator find( int * const & key ) const;

使用类型为const int*的变量无法调用此类函数。这将允许函数打破指针指向的对象的const - 。