从“const int*”到“int*”的无效转换

bar*_*rej 1 c++ pointers casting compiler-errors

我收到以下错误

\n\n
$ g++ test.cpp\ntest.cpp: In function \xe2\x80\x98int test1(const int**, int)\xe2\x80\x99:\ntest.cpp:11:14: error: invalid conversion from \xe2\x80\x98const int*\xe2\x80\x99 to \xe2\x80\x98int*\xe2\x80\x99 [-fpermissive]\n         a=v[i];\n              ^\ntest.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\ntest.cpp:31:20: error: invalid conversion from \xe2\x80\x98int**\xe2\x80\x99 to \xe2\x80\x98const int**\xe2\x80\x99 [-fpermissive]\n     cout<<test1(c,2)<<endl;\n                    ^\ntest.cpp:4:5: error:   initializing argument 1 of \xe2\x80\x98int test1(const int**, int)\xe2\x80\x99 [-fpermissive]\n int test1(const int **v,int num)\n     ^\n
Run Code Online (Sandbox Code Playgroud)\n\n

编译以下代码时:

\n\n
#include <iostream>\nusing namespace std;\n\nint test1(const int **v,int num)\n{\n    int *a;\n    int result=0;\n    // do somethings ....\n    for(int i=0;i<num;i++)\n    {\n        a=v[i];\n        // do somethings ....\n        result+=*a;\n    }\n    return result;\n}\n\nvoid test2(const int num)\n{\n    cout<<num<<endl;\n}\n\nint main()\n{\n    int a =5;\n    int b =8;\n    int **c;\n    c=new int *[2];\n    c[0]=&a;\n    c[1]=&b;\n    cout<<test1(c,2)<<endl;\n    test2(a);\n    delete [] c; \n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我给了inttest2 要求的const int,就可以了。但是 test1 不接受int **代替const int **.

\n\n

在上面的代码中,即使类型转换也不起作用:

\n\n
a=(int *)v[i];\n
Run Code Online (Sandbox Code Playgroud)\n\n

AFAIK,const 意味着我保证不会改变 的值,v而我没有。但是,编译器给了我错误。

\n

Win*_*ute 5

写吧

int const *a;  // or const int *a; which is the same.
Run Code Online (Sandbox Code Playgroud)

...那么 const 的正确性将被保留。编译器会抱怨,因为您尝试分配v[i](这是一个int const *, to ),通过它可以更改承诺不会更改的int *元素。v由于您稍后不会尝试这样做,因此只需使用 anint const*来让编译器放心。

请注意,它将a仍然是一个指针变量(因此您将能够重新分配它),只是它将指向整数常量(您不能通过 更改a)。要声明常量指针,您可以编写

int       *const a; // pointer constant to int variable,or
int const *const a; // pointer constant to int constant
Run Code Online (Sandbox Code Playgroud)

另一个错误的起源类似,尽管很难理解为什么它被禁止(因为您只是添加const而不是试图将其删除)。int**考虑一下:如果允许从to进行赋值int const **,您可以编写以下代码:

int const data[] = { 1, 2, 3, 4 }; // this is not supposed to be changed.

int *space;
int **p = &space;
int const **p2 = p; // this is not allowed. Were it allowed, then:

*p2 = data;
**p = 2;     // this would write to data.
Run Code Online (Sandbox Code Playgroud)

那会很糟糕,嗯。如果你改为写

int test1(const int *const *v, int num)
Run Code Online (Sandbox Code Playgroud)

现在v是一个指向 int 常量的指针常量的指针(变量)。由于*v是常数,因此漏洞已被关闭,编译器将接受它。