C++ 中具有常量的数组的指针和引用
Pointer and References to Array with Consts in C++
我很清楚 const pointer to pointer problem,我以为我知道发生了什么,但我错了。我想实现这个:
int* var[4];
const int* const (&refArray)[4] = var; //compile error
是的,我想保留数组而不是转换为指针,是的,我在我的代码中确实遇到了这个问题。所以我继续调查我能做什么和不能做什么,不久我意识到我不知道发生了什么:
int* var[4];
const int* const * ptr = var; //allowed
const int* const * (&refPtr_indirect) = ptr; //allowed
const int* const * (&refPtr) = var; //error
const int* const * const (&constRefPtr) = var; //allowed
int* const (&refArray)[4] = var; //allowed
const int* const (&refArray)[4] = var; //error
前四个我能理解,但后两个对我来说完全没有意义。我确实看到第三个版本可能有效并且我可以删除 reference
,但我真的希望保留数组类型。
感谢任何帮助,但希望它可以包括 为什么 规则保持原样背后的原因。
您有一个包含四个指向(非常量)int
的指针的数组。要将其视为指向 const int
的四个指针的数组,您需要使用类型双关语。 int [4]
和 const int [4]
类型不同,对一个的引用不能引用另一个。
你能做的最好的事情就是对整个数组进行常量引用。在像这样的复杂情况下,最好使用一些类型名称以便于管理:
typedef int* TheArray[4];
TheArray var;
const TheArray &ref = var;
这给你这个:
ref[0]; // OK
ref[0] = nullptr; // error
*ref[0]; // OK
*ref[0] = 42; // OK
你的第五个版本是一样的,只是没有类型名称
int * const (&refArray) [4] = var;
对指向 int
的四个指针的常量数组的引用。 (常量数组与常量元素数组相同)。
第六个版本不可能工作,正如我在顶部所说的那样——数组元素的类型不同,因此没有引用可以同时引用它们。
Angew 得到了一些分数,但我认为问题在于:
您无法将 int*[n]
转换为 const int*[n]
。
所以这是允许的:
int a[4];
const int (&b)[4] = a;
但以下不是:
int *c[4];
const int *(&d)[4] = c;
我很清楚 const pointer to pointer problem,我以为我知道发生了什么,但我错了。我想实现这个:
int* var[4];
const int* const (&refArray)[4] = var; //compile error
是的,我想保留数组而不是转换为指针,是的,我在我的代码中确实遇到了这个问题。所以我继续调查我能做什么和不能做什么,不久我意识到我不知道发生了什么:
int* var[4];
const int* const * ptr = var; //allowed
const int* const * (&refPtr_indirect) = ptr; //allowed
const int* const * (&refPtr) = var; //error
const int* const * const (&constRefPtr) = var; //allowed
int* const (&refArray)[4] = var; //allowed
const int* const (&refArray)[4] = var; //error
前四个我能理解,但后两个对我来说完全没有意义。我确实看到第三个版本可能有效并且我可以删除 reference
,但我真的希望保留数组类型。
感谢任何帮助,但希望它可以包括 为什么 规则保持原样背后的原因。
您有一个包含四个指向(非常量)int
的指针的数组。要将其视为指向 const int
的四个指针的数组,您需要使用类型双关语。 int [4]
和 const int [4]
类型不同,对一个的引用不能引用另一个。
你能做的最好的事情就是对整个数组进行常量引用。在像这样的复杂情况下,最好使用一些类型名称以便于管理:
typedef int* TheArray[4];
TheArray var;
const TheArray &ref = var;
这给你这个:
ref[0]; // OK
ref[0] = nullptr; // error
*ref[0]; // OK
*ref[0] = 42; // OK
你的第五个版本是一样的,只是没有类型名称
int * const (&refArray) [4] = var;
对指向 int
的四个指针的常量数组的引用。 (常量数组与常量元素数组相同)。
第六个版本不可能工作,正如我在顶部所说的那样——数组元素的类型不同,因此没有引用可以同时引用它们。
Angew 得到了一些分数,但我认为问题在于:
您无法将 int*[n]
转换为 const int*[n]
。
所以这是允许的:
int a[4];
const int (&b)[4] = a;
但以下不是:
int *c[4];
const int *(&d)[4] = c;