为什么在c++中不能将int**转换为const int**
why cant int** be converted to const int** in 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;
}
int **
是:"指向整数的指针"const int **
是:"指向常量整数的指针的指针"
一个牵强的类比:
- 一个说明另一个说明罐子位置的说明
- 描述另一个注释的位置的注释,该注释描述已关闭jar的位置
你只能把一块饼干放在一个没有关上的罐子里。
现在,考虑用第一个音符的复印件替换第二个音符。你有任何保证吗,这张纸条指向的最终罐子将被关闭,不能接受任何cookie?const
的使用是一种契约,不能通过间接引用两个引用来满足这种契约。
基本上,这是因为通过更改间接级别和其他有效的、非const违反语义,如果const仅在顶级,则可以绕过它。您必须在多个级别上添加const,才能使const真正安全。
编辑:
你违反了常量正确性。通过说您想要一个pointer-to--pointer,您就是通过允许修改原始const对象来设置自己。Const是一份合同。通过允许这种情况在没有强制转换的情况下发生,您将自己设置为允许稍后修改const对象。
相关文章:
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 将字符串中的 int 转换为字母;
- 主.cpp:18:20:错误:从"int*"转换为"int"会失去精度 [-fa
- 将非常大的 int 转换为双倍,在某些计算机上会损失精度
- 如何将矢量<int>转换为字符数组?
- C++ 无法从 const int* 转换为 const_iterator
- 我不断收到错误 C2440'=':无法从"int *(__cdecl *)(int *,int *,int,int)"转换为"int *
- 如何将 int[4] 转换为 std::array<int,4>?
- 如何将data[i].int转换为vaible
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 将私有矩阵形式 int 转换为双 C++
- 无法将参数 1 从 'int' 转换为 'int &'
- 将 int 转换为字符串后始终得到 0
- isspace 函数的性能警告,从 int 转换为布尔值
- 将大 int 转换为浮点数,而不舍入 c++
- 错误:无法将'uint8* {aka unsigned int*}'转换为"常量emxArray_uint8_T*"?
- 将未签名的INT转换为BCD
- 在 C++ 中将 int 转换为双精度