"reference to array" 类型的表示法
Notation for "reference to array" type
在c++中,数组引用的类型显示为int (&) [10]
。例如,当我尝试使用 g++ 编译并发出以下代码
template <typename T> void foo(T&);
int main() {
int a[] {1, 2, 3};
foo(a);
}
我收到以下错误:
undefined reference to `void foo<int [3]>(int (&) [3])'
在这个错误文本中,为什么参数类型显示为 int (&) [3]
?为什么我们不表示数组引用类型,例如对整数类型或 class 类型的引用,即 int [10] &
?使用(&)
的原因是什么?
我知道我们可以这样定义一个 'reference to array' 变量:
int (&b)[3] = a;
而这个定义确实是'looks like'b的类型。但这是唯一的原因吗? int [10] &
符号有问题吗?
它来自数组指针的类型:int(*)[10]
。 *
只是替换为 &
,就像在所有引用类型中一样。
指向数组的指针看起来像那样的原因是它在 C 中的样子,而 C++ 没有理由改变它。
int (*a)[10];
// "(*a)[10]" is an int
// The type of `a` is `int (*)[10]`, just remove the name
我没有看到任何技术原因,为什么 int[10]*
和 int[10]&
不能作为“指针或对 10 个数组的引用的类型名称” int
",除了与 C
的兼容性
在c++中,数组引用的类型显示为int (&) [10]
。例如,当我尝试使用 g++ 编译并发出以下代码
template <typename T> void foo(T&);
int main() {
int a[] {1, 2, 3};
foo(a);
}
我收到以下错误:
undefined reference to `void foo<int [3]>(int (&) [3])'
在这个错误文本中,为什么参数类型显示为 int (&) [3]
?为什么我们不表示数组引用类型,例如对整数类型或 class 类型的引用,即 int [10] &
?使用(&)
的原因是什么?
我知道我们可以这样定义一个 'reference to array' 变量:
int (&b)[3] = a;
而这个定义确实是'looks like'b的类型。但这是唯一的原因吗? int [10] &
符号有问题吗?
它来自数组指针的类型:int(*)[10]
。 *
只是替换为 &
,就像在所有引用类型中一样。
指向数组的指针看起来像那样的原因是它在 C 中的样子,而 C++ 没有理由改变它。
int (*a)[10];
// "(*a)[10]" is an int
// The type of `a` is `int (*)[10]`, just remove the name
我没有看到任何技术原因,为什么 int[10]*
和 int[10]&
不能作为“指针或对 10 个数组的引用的类型名称” int
",除了与 C