c++ - const TypedeffedIntPointer 不等于 const int *

标签 c++

我有以下 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/

相关文章:

c++ - 我在让 qwt 小部件与 Qt-Creator 正常工作时遇到问题

c++ - stdio.h 和 iostream 有什么区别?

c++ - 帮助指针和传递链表作为参数, undefined reference C++

c++ - 在 QTextEdit 中,您如何检测用户何时仅将光标插入文本区域一次?

c++ - 包装 unordered_map 以构建不可修改(不可变)的映射

c++ - C++切换以按住鼠标左键吗?

c++ - MapViewOfFile 中信号量的最佳方法 - C++

C++ 文本完全对齐

c++ - 这个 C++ 列表有什么问题?

c++ - 我如何将多态属性与 boost::spirit::qi 解析器一起使用?