我有以下 C++ 代码:
typedef int* IntPtr;
const int* cip = new int;
const IntPtr ctip4 = cip;
我用 Visual Studio 2008 编译它并得到以下错误:
error C2440: 'initializing' : cannot convert from 'const int *' to 'const IntPtr'
显然我对 typedef 的理解不应该是这样。
我问的原因是,我将指针类型存储在 STL 映射中。我有一个返回常量指针的函数,我想用它在 map 中进行搜索(使用 map::find(const key_type&)。因为
const MyType*
和
const map<MyType*, somedata>::key_type
不兼容,我遇到了问题。
问候 德克
最佳答案
当您编写 const IntPtr ctip4
时,您声明了一个const-pointer-to-int,而 const int * cip
声明了一个指向常量整数的指针。它们不相同,因此无法转换。
需要将cip的声明/初始化改为
int * const cip = new int;
要在您的示例中解决此问题,您需要将 map 的键类型更改为 const MyType *
(是否有意义取决于您的应用程序,但我认为改变通过用作映射中键的指针的 MyType 对象是不太可能的),或者回退到 const_casting 参数来查找:
#include <map>
int main()
{
const int * cpi = some_func();
std::map<const int *, int> const_int_ptr_map;
const_int_ptr_map.find(cpi); //ok
std::map<int *, int> int_ptr_map;
int_ptr_map.find(const_cast<int *>(cpi)); //ok
}
关于c++ - const TypedeffedIntPointer 不等于 const int *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2781798/