从'const int *'到'int *'的无效转换

时间:2014-12-12 15:49:22

标签: c++ pointers casting compiler-errors

我收到以下错误

$ 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的值而我没有。但是,编译器给我错误。

1 个答案:

答案 0 :(得分:4)

只需写下

int const *a;  // or const int *a; which is the same.

...然后将保留const正确性。编译器会抱怨,因为您尝试将v[i] int const *分配给int *v承诺不会更改的元素可以通过该int const*进行更改。由于您以后不想尝试这样做,只需使用a来安抚编译器。

请注意a将保持指针变量(因此您可以重新分配它),只会指向整数常量(然后您无法通过int *const a; // pointer constant to int variable,or int const *const a; // pointer constant to int constant 更改)。要声明一个常量指针,你可以写

const

另一个错误在起源上是相似的,虽然它有点难以理解为什么它被禁止(因为你只是添加int**而不是试图把它带走) 。考虑一下:如果允许从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. 进行分配,您可以编写以下代码:

int test1(const int *const *v, int num)

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

v

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