为什么下面的 c++ 代码无法编译?

Why the following c++ code don't compile?

本文关键字:编译 代码 c++ 为什么      更新时间:2023-10-16
#include <iostream>
int test( const double *t1,const double **t2 )
{
  return 0;
}
int main(int argc, char*argv[])
{
  double *t1 = new double;
  const double ** t2 = new double *;
  test(t1, t2);
}

错误为:

cannot convert double ** to const double **

如果我删除const的2个出现,它就会编译。。

使其成为

const double ** t2 = new const double *;

问题是,通过以某种方式取消引用,您可能会使用双指针违反常量正确性。

这样的转换是不允许的,因为如果转换是可能的,您可以通过以下方式修改const对象:

#include <stdio.h>
const double A0 = 0;
const double A1 = 1;
const double* A[2] = { &A0, &A1 };
double * B[2];
int main()
{
  double** b = B;
  const double ** a = b; // illegal
  //const double ** a = (const double **)b; // you can simulate it would be legal
  a[0] = A[0];
  b[0][0] = 2; // modified A0
  printf("%f",A[0][0]);
}

对于模拟结果,请查看IdeOne.com上的代码-您将获得SIGSEGV(const对象被放置在只读内存中,您正在尝试修改它(。使用不同的平台,对象可能会被静默地修改。

现在至少应该编译

int main(int argc, char*argv[])
{
  double *t1 = new double;
  const double ** t2 = new const double *;
  test(t1, t2);
}