const TypedeffedIntPointer不等于const int * [英] const TypedeffedIntPointer not equal to const int *
问题描述
我有以下C ++代码:
I have the following C++ code:
typedef int* IntPtr;
const int* cip = new int;
const IntPtr ctip4 = cip;
我使用Visual Studio 2008编译,并得到以下错误:
I compile this with Visual Studio 2008 and get the following error:
错误C2440:'initializing':无法从'const int *'转换为'const IntPtr'
error C2440: 'initializing' : cannot convert from 'const int *' to 'const IntPtr'
显然,我对typedef的理解不是应该的。
Clearly my understanding of typedefs is not what is should be.
我问的原因是,我在一个指针类型STL映射。我有一个函数返回一个const指针,我想用它来搜索地图(使用map :: find(const key_type&))。
The reason I'm asking, I'm storing a pointer type in a STL map. I have a function that returns a const pointer which I would like to use to search in the map (using map::find(const key_type&). Since
const MyType*
和
const map<MyType*, somedata>::key_type
$ b b
不兼容,我遇到问题。
is incompatible, I'm having problems.
尊敬的
Dirk
Regards Dirk
推荐答案
当你写 const IntPtr ctip4
时,你要声明一个 const-pointer-to-int code> const int * cip 声明一个 pointer-to-const-int 。这些不一样,因此转换是不可能的。
When you write const IntPtr ctip4
, you are declaring a const-pointer-to-int, whereas const int * cip
declares a pointer-to-const-int. These are not the same, hence the conversion is impossible.
您需要将cip的声明/初始化更改为
You need to change the declaration/initialization of cip to
int * const cip = new int;
要解决此示例中的此问题,您需要更改映射到 const MyType *
(无论它是否有意义取决于您的应用程序,但我认为通过在地图中用作键的指针更改MyType对象不太可能) ,或者返回const_casting参数以查找:
To resolve this issue in your example, you need to either change the key type of the map to const MyType *
(whether or not it makes sense depends on your application, but I think that changing a MyType object via a pointer used as key in the map is unlikely), or fall back to const_casting the parameter to find:
#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
}
这篇关于const TypedeffedIntPointer不等于const int *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!