【发布时间】:2014-05-23 15:15:41
【问题描述】:
我使用的是 gcc 版本 4.5.0。使用下面的简单示例,我会假设得到一个错误 invalid conversion from double* to const double*
#include <iostream>
using namespace std;
void foo(const double *a)
{
cout<<a[0]*2.<<endl;
}
int main()
{
double *a=new double[2];
a[0]=1.;
a[1]=2.;
foo(a);
return 1;
}
为什么编译没有错误?
反例如下:
#include<iostream>
using namespace std;
void foo(const double **a)
{
cout<<a[0][0]*2.<<endl;
}
int main()
{
double **a=new double*[2];
a[0]=new double[2];
a[1]=new double[2];
a[0][0]=1.;
foo(a);
cout<<a[0][0]<<endl;
return 1;
}
(第二个示例的解决方案:将 foo 定义为 foo(const double*const* a)。感谢 Jack Edmonds 的评论,这解释了错误消息)
【问题讨论】:
-
为什么转换无效?
-
因为在使用双 **a 的情况下会出现转换错误。