可能重复:
why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)为什么不能INT **转换成const int的**在C++
您好我有下面的代码,但不能换我周围为什么这头不起作用 - 我得到一个错误,说“不能从int **转换为const int **”。但是,如果我将printValues的第一个参数更改为“const int * const * myArray”,则一切正常。我知道我可能不应该使用下面的那个,但我不明白它为什么不能编译。你可以不用一个指向常量整数的指针而不用在main()中声明它的常量吗?
#include <iostream>
int printValues(const int ** myArray, const long nRows, const long nCols)
{
for (long iRow = 0; iRow < nRows; iRow++)
{
for (long iCol = 0; iCol < nCols; iCol++)
{
std::cout << myArray[iRow][iCol] << " ";
}
std::cout << "\n";
}
return 0;
}
int main()
{
const long nRows = 5;
const long nCols = 8;
int** myArray = new int* [nRows];
for (long iRow = 0; iRow < nRows; iRow++)
{
myArray[iRow] = new int [nCols];
}
for (long iRow = 0; iRow < nRows; iRow++)
{
for (long iCol = 0; iCol < nCols; iCol++)
{
myArray[iRow][iCol] = 1;
}
}
printValues(myArray, nRows, nCols);
return 0;
}
请参阅[“为什么我的转换Foo **→Foo常量**”出错?](http://www.parashift.com/c++-faq-lite/const-correctness.html#faq- 18.17) –
因为它实际上允许你违反const正确性。我会尽力找到dup。 –
我从来没有意识到这是一个很受欢迎的问题,在我看到的所有答案中,我感觉[标准之一](http://stackoverflow.com/a/29240053/1708801)是最好的。 –