如何使类型别名"a pointer to an array of const int"?
How to make type alias to "a pointer to an array of const int"?
我正在做关于类型别名的练习(ex3.44 c++ Primer 5th)。下面的代码将使:
-
指向const int类型数组的指针的类型别名,
-
const int数组引用的类型别名
然而,结果不符合预期(见注释)。为什么?
int main(){
int ia[3] = {0, 1, 2};
typedef const int (*cpa)[3];
cpa g = 0; //(gdb) ptype g: type = int (*)[3]
typedef const int (&cra)[3];
cra h = ia; //(gdb) ptype h: type = int (&)[3]
return 0;
}
当我删除数组时,它按预期工作。参见下面的代码:
int main(){
int i = 42;
typedef const int* cp;
cp e = &i; //(gdb) ptype e: type = const int *
typedef const int& cr;
cr f = i; //(gdb) ptype f: type = const int &
return 0;
}
最后一件事,如果使用"using"关键字,如何重写别名定义?
这只是省略了const
的gdb
版本的输出。const
仍然很重要。我们可以用下面这个无法编译的程序来证明:
int main(){
const int ia[3] = {0, 1, 2};
typedef int (*cpa)[3];
cpa g = 0;
typedef int (&cra)[3];
cra h = ia;
return 0;
}
对于我来说,使用gdb 7.7,输出如预期:
(gdb) ptype g
type = const int (*)[3]
(gdb) ptype h
type = const int (&)[3]
用using
重写这些typedef
s:
using cpa = const int (*)[3];
using cra = const int (&)[3];
您可以看到模式只是using identifier =
后面跟着缺少标识符的声明。
你太相信gdb了。它省略了"const",原因我不明白。您应该用其他方法验证类型的正确性。一种方法是赋值给g[0]。这将给您一个错误,其中包含如下消息:
error: incompatible types in assignment of ‘int’ to ‘const int [3]’
马上告诉你你的问题不存在。
还可以使用typeid从编译器获取类型并打印出来。在vc++中,这样做很简单。使用gcc时,您需要调整结果以使其可读。下面的代码输出g和g2的类型,带const和不带const。
#include <stdio.h>
#include <typeinfo>
#ifdef __GNUG__
#define DEMANGLE
#endif
#ifdef DEMANGLE
#include <cxxabi.h>
#endif
template <typename T>
const char* TypeName(const T& type)
{
#ifdef DEMANGLE
int status = 0;
// Convert the cryptic gcc name decorations to something
// human readable.
return abi::__cxa_demangle(typeid(type).name(), NULL, NULL, &status);
#else
return typeid(type).name();
#endif
}
int main(){
int ia[3] = {0, 1, 2};
typedef const int (*cpa)[3];
cpa g = 0; //(gdb) ptype g: type = int (*)[3]
typedef int (*cpa2)[3];
cpa2 g2 = 0; //(gdb) ptype g: type = int (*)[3]
typedef const int (&cra)[3];
cra h = ia; //(gdb) ptype h: type = int (&)[3]
printf("Type of 'g' is '%s'n", TypeName(g));
printf("Type of 'g2' is '%s'n", TypeName(g2));
//g[0] = 2; This fails to compile, thus proving that cpa/g have the correct type.
return 0;
}
相关文章:
- constexpr begin of a std::array
- Divide et impera sum of the elements of an array bug
- Initialize std::array of std::array
- Array Manipulation of HackerRank 背后的逻辑
- Array of vtkSmartPointers
- 混淆从"array of int[]"到"pointer to int"的显式衰减?
- VC++ 2010 "array is not a member of std"错误
- C语言中有没有类似'minimizing stack overflow of an array'的东西?
- 什么是指向 C 语言中'array of characters'的指针?
- Qt QVector of multidimensional array
- 应对"Bring all the zeros to the back of the array"面试挑战的良好C++解决方案
- 为什么我会得到"cannot allocate an array of constant size 0"?
- "address of array"的实际用例是什么?
- Array of a Struct C++
- MATLAB array of libpointer
- std::vector of an array
- Array of Vectors C++
- C++错误:"taking address of temporary array"
- C++编译错误:"Double array redeclared as different kind of symbol"
- 如何使类型别名"a pointer to an array of const int"?