有人問到傳數組名,和數組名引用的問題,平時沒怎麼使用這麼怪異的語法
沒有想明白;後來在水木清華上諮詢到了清晰的解答,現深入總結如下:
例子:
#include <iostream>
#include <typeinfo>
using namespace std;
void fArray(int *a, int b[], int (*c)[4], int (&ra)[4], int d[4])
{
cout << "In fArray(...):" << endl;
cout << "int* a type " << typeid(a).name() << endl;
cout << "int b[] type " << typeid(b).name() << endl;
cout << "int (*c)[4] type " << typeid(c).name() << endl;
cout << "int (&ra)[4] type " << typeid(ra).name() << endl;
cout << "int d[4] type " << typeid(d).name() << endl;
return;
}
int main()
{
int a[4] = {1,2,3,4};
int (&ra)[4] = a;
cout << "In main():" << endl;
cout << "int a[4] type " << typeid(a).name() << endl;
cout << "int (&ra)[4] type " << typeid(ra).name() << endl;
fArray(a,a,&a,a,a);
return 0;
}
g++ 4.4.1結果:
In main():
int a[4] type A4_i
int (&ra)[4] type A4_i
In fArray(...):
int* a type Pi
int b[] type Pi
int (*c)[4] type PA4_i
int (&ra)[4] type A4_i
int d[4] type Pi
main()裏面a ra都是int[4]類型
而作爲形參int(&ra)[4],int d[4]怎麼類型就不一致呢,是否語義不一致?
水木清華jasss回答如下,仔細重看了標準相關內容,確實如此。
Because we have a standard array-to-pointer
conversion here, and here the argument
int d[4]
is same as
int *d
, and the array size 4 is meaningless here.
For int (&ra)[4], here ra is a reference to
an array with 4 int element, array a is <br /><ul><li></li></ul><br /><br /><div class="zemanta-pixie"><img class="zemanta-pixie-img" alt="" src="http://img.zemanta.com/pixy.gif?x-id=187432ac-8829-830d-adaf-928cb9997ed7" /></div>
bound to ra directly.
: 這不會導致int a[4]和int d[4]存在語義不一致嗎?
The two function arguments are different...
For ra, the size information is part of the type
and d is merely a pointer.
For example, changing arguemnt ra to "int (&ra)[5]"
then the program won't compile, while the compiler
does not care even you replacing "int d[4]" with
"int d[5]".