【问题标题】:C++ non const to const casting compilation errorC++ 非 const 到 const 转换编译错误
【发布时间】:2012-03-14 17:50:32
【问题描述】:

以下代码无法编译

void aaa(const int **a) {
}

int *a[] = {new int[2]};
aaa(a);

在 VS2010 中出现“无法将参数 1 从 'int [1]' 转换为 'const int *”,在 gcc 中出现类似错误

当我将声明更改为:

int const *a[] = {new int[2]};

const int *a[] = {new int[2]};

它可以编译,但我不明白为什么它不接受非 const 变量声明

【问题讨论】:

    标签: c++ casting const-cast


    【解决方案1】:

    a 的类型是int*[];你想要的类型是int const**int*[] 转换为 int**,但这不会隐式转换为 int const**。请考虑以下代码以了解原因:

    static int const ci = 42;
    
    void aaa( int const** out )
    {
        *out = &ci;
    }
    
    int
    main()
    {
        int* pa;
        aaa( &pa );     //  NOT LEGAL, because...
        *pa = 0;        //  would now change ci
        std::cout << ci << std::endl;
        return 0;
    }
    

    如您所见,允许这种转换会破坏 const 需要演员表。

    根据你正在做的事情,你可能想要使用:

    void aaa( int const* const* out );
    

    int**int const *const * 的隐式转换是合法的。 (否则,您需要在某处使用const_cast 来告诉编译器 你知道你在做什么,这不是一个真正的问题。)

    【讨论】:

    • 也许aaa(&amp;pa) 应该是aaa(pa)
    • @tinybit 或者它的声明应该是int* pa;,调用后的使用应该是*pa = 0;。我将编辑以修复我的答案中的代码。感谢您发现这一点。
    【解决方案2】:

    函数aaa 需要一个指向常量的指针。 您的变量 a 是一个指向 int 的指针。 将后者分配给前者是错误的。

    int const *a[]const int *a[]其实是同一个东西,匹配aaa的签名。如果你尝试int * const a[],那将是不同的类型(指针到常量指针到整数),你会再次触发类型错误。

    如果您希望您的函数aaa 采用常量指针到指针到int,您需要编写aaa(int ** const a),但参数值的常量实际上对您的内容没有影响可以打电话。


    编辑: “但不是隐式添加 constness - 通过隐式转换完成吗?(这是实际问题)”

    常量可以隐式添加到您传递的值中,例如

    void aaa(const int a) {}
    
    int b=5;
    aaa(b);
    

    ...或一级指针

    void aaa(const int* a) {}
    
    int *b=new int;
    aaa(b);
    

    ...但不能更深地添加。例如这是无效的:

    void aaa(const int** a) {}
    
    int* b=new int;
    int** c=&b;
    aaa(c);
    

    我认为 James Kanze 在他的回答中解释得更好。

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多