为什么cant int **在c ++中被转换为const int **

时间:2011-06-21 16:40:36

标签: c++

  

可能重复:
  why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

您好我有以下代码,但无法解决为什么这不起作用 - 我得到一个错误说“无法从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;
}

3 个答案:

答案 0 :(得分:6)

  • int **是:“指向整数的指针”。
  • const int **是:“指向常量整数的指针”。

一个牵强附会的类比:

  • 描述另一个描述jar位置的音符位置的注释
  • 描述描述已关闭 jar
  • 位置的另一个音符的位置的注释

您只能将一个cookie放在未关闭的jar中。

现在,考虑用第一个音符的复印件替换第二个音符。您是否保证本说明所指出的最终罐子将被关闭且不能接受任何饼干?使用const是一个合同,你不能通过两个引用的间接来满足这个合同。

答案 1 :(得分:1)

编辑:

你违反了const-correctness。通过说你想要一个指向指针的指针,你可以通过允许修改原始const对象来设置自己。 Const是一份合同。通过允许在没有强制转换的情况下发生这种情况,您可以自行设置以便稍后修改const对象。

答案 2 :(得分:1)

基本上,这是因为它可以通过改变间接的级别和其他有效的,非违反语义,如果它只在顶层,你可以解决const。你必须在多个级别上添加const才能使const真正安全。

相关问题