【发布时间】:2014-07-05 15:43:52
【问题描述】:
我正在做关于类型别名的练习(ex3.44 C++ Primer 5th)。 下面的代码将使:
指向 const int 数组的指针的类型别名,以及
对 const int 数组的引用的类型别名
但是结果与预期不符(参见 cmets)。为什么?
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”关键字,如何重写别名定义?
【问题讨论】:
-
为什么不符合您的预期?
-
@Joseph Mansfield 缺少常量
-
这些是对的,
using使事情变得更容易,因为您不需要在混乱中使用名称。顺便说一句,您也可以在编译时检查。const int arr[3]; static_assert(std::is_same<cpa, decltype(&arr)>::value, ""); -
@chris 但是如果使用数组,则缺少“const”
-
@user3701346,如果你的意思是
static_assert,它不是一个函数,也不是一个宏,而是一个声明(static-assert-declaration)。如果您的意思是decltype,它是一个说明符。如果你的意思是std::is_same,它是一个类型特征(基本上只是一个带有value成员的结构)。
标签: c++ arrays pointers alias typedef