下面的代码无法编译
void aaa(const int **a) {
}
int *a[] = {new int[2]};
aaa(a);
我在 VS2010 中遇到“无法将参数 1 从‘int [1]’转换为‘const int *”,在 gcc 中遇到类似错误
当我将声明更改为:
int const *a[] = {new int[2]};
或
const int *a[] = {new int[2]};
它可以编译,但我不明白为什么它不接受非 const 变量声明
最佳答案
a
的类型是int*[]
;您想要的类型是 int const**
。
int*[]
转换为 int**
,但这不会隐式转换为
整数常量**
。考虑以下代码以了解原因:
static int const ci = 42;
void aaa( int const** out )
{
*out = &ci;
}
int
main()
{
int* pa;
aaa( &pa ); // NOT LEGAL, because...
*pa = 0; // would now change ci
std::cout << ci << std::endl;
return 0;
}
如您所见,允许此转换会破坏常量 需要类型转换。
根据你在做什么,你可能想使用:
void aaa( int const* const* out );
int**
到int const *const *
的隐式转换是合法的。
(否则,您需要在某处使用 const_cast
来告诉编译器
你知道自己在做什么,这不是真正的问题。)
关于C++ 非 const 到 const 转换编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9428044/