【发布时间】:2014-12-12 15:49:22
【问题描述】:
我收到以下错误
$ g++ test.cpp
test.cpp: In function ‘int test1(const int**, int)’:
test.cpp:11:14: error: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive]
a=v[i];
^
test.cpp: In function ‘int main()’:
test.cpp:31:20: error: invalid conversion from ‘int**’ to ‘const int**’ [-fpermissive]
cout<<test1(c,2)<<endl;
^
test.cpp:4:5: error: initializing argument 1 of ‘int test1(const int**, int)’ [-fpermissive]
int test1(const int **v,int num)
^
编译以下代码时:
#include <iostream>
using namespace std;
int test1(const int **v,int num)
{
int *a;
int result=0;
// do somethings ....
for(int i=0;i<num;i++)
{
a=v[i];
// do somethings ....
result+=*a;
}
return result;
}
void test2(const int num)
{
cout<<num<<endl;
}
int main()
{
int a =5;
int b =8;
int **c;
c=new int *[2];
c[0]=&a;
c[1]=&b;
cout<<test1(c,2)<<endl;
test2(a);
delete [] c;
return 0;
}
我给 test2 一个int,它要求const int,没关系。但是 test1 不接受 int ** 而不是 const int **。
在上面的代码中,甚至类型转换都不起作用:
a=(int *)v[i];
AFAIK, const 表示我保证不会更改v 的值,但我没有。但是,编译器给了我错误。
【问题讨论】:
-
const int**应该是int* const* -
@PiotrS。实际上它可能应该是
int const * const *,因为该函数不会修改传入数组中的指针,也不会修改它们指向的值。 -
似乎有很多 C++ 不需要的指针。
标签: c++ pointers casting compiler-errors