【问题标题】:invalid conversion from ‘const int*’ to ‘int*’从‘const int*’到‘int*’的无效转换
【发布时间】: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


【解决方案1】:

随便写

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.

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

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

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

【讨论】:

    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2012-03-30
    相关资源
    最近更新 更多