为什么在c++中不能将int**转换为const int**

why cant int** be converted to const int** in c++

本文关键字:int 转换 const c++ 不能 为什么      更新时间:2023-10-16

可能重复:
为什么将(指向非常数的指针)转换为(指向常量的指针)不合法

嗨,我有以下代码,但我无法理解为什么这不起作用——我收到一个错误,说"无法从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;
}
  • int **是:"指向整数的指针"
  • const int **是:"指向常量整数的指针的指针"

一个牵强的类比:

  • 一个说明另一个说明罐子位置的说明
  • 描述另一个注释的位置的注释,该注释描述已关闭jar的位置

你只能把一块饼干放在一个没有关上的罐子里。

现在,考虑用第一个音符的复印件替换第二个音符。你有任何保证吗,这张纸条指向的最终罐子将被关闭,不能接受任何cookie?const的使用是一种契约,不能通过间接引用两个引用来满足这种契约。

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

编辑:

你违反了常量正确性。通过说您想要一个pointer-to--pointer,您就是通过允许修改原始const对象来设置自己。Const是一份合同。通过允许这种情况在没有强制转换的情况下发生,您将自己设置为允许稍后修改const对象。