C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – const TypedeffedIntPointer不等于const int *大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下C代码

typedef int* IntPtr;
const int* cip = new int;
const IntPtr ctip4 = cip;

我用Visual studio 2008编译它并得到以下错误

显然,我对typedef的理解不是应该的.

我问的原因是,我将指针类型存储在STL映射中.我有一个函数返回一个const指针,我想用它在地图中搜索(使用map :: find(const key_type&)).

const myType*

const map<myType*,somedata>::key_type

是不相容的,我有问题.

问候
短剑

解决方法

当你编写const IntPtr ctip4时,你声明一个const-pointer-to-int,而const int * cip声明一个指向const-int的指针.这些不一样,因此转换是不可能的.

您需要将cip的声明/初始化更改为

int * const cip = new int;

要在您的示例中解决此问题,您需要将映射的键类型更改为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 *全部内容,希望文章能够帮你解决c – const TypedeffedIntPointer不等于const int *所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。