【问题标题】:c++ const convert [duplicate]c ++ const转换[重复]
【发布时间】:2011-08-18 14:23:18
【问题描述】:

可能重复:
why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

我有一个函数:

bool isCirclePolygonIntersection(const Point*, const int*, const Point*,
                                 const Point**, const int*);

我试图这样称呼它:

isCirclePolygonIntersection(p, &r, poly_coord, poly, &poly_size)

poly 的定义如下:

Point** poly = new Point*[poly_size];

当我尝试编译时出现编译器错误:

error C2664: 'isCirclePolygonIntersection' : cannot convert parameter 4 from 'Point **' to 'const Point **'
1>          Conversion loses qualifiers

据我所知,当函数需要非 const 参数时,您不能将 const 参数提供给函数,但否则没关系。 有谁知道是什么问题?? 谢谢。

【问题讨论】:

  • 如果您声明参数const Point *const *,它将起作用。 (嗯,它可以在 C++ 中工作,而不是在 C 中。)

标签: c++ compiler-construction casting constants


【解决方案1】:

你是对的;您可以T * 隐式转换为const T *。但是,您不能T ** 隐式转换为const T **。请参阅 C 常见问题解答:http://c-faq.com/ansi/constmismatch.html

【讨论】:

    【解决方案2】:

    Point**const Point** 的隐式转换会在类型系统中打开一个漏洞,因此在 C++ 中没有这种转换。

    详情见Why am I getting an error converting a Foo**Foo const**?

    const Point** 更改为const Point * const * 将解决您的问题。

    顺便问一下,为什么要附加间接性?也就是说,为什么要使用指针数组?我建议改为std::vector<Point>。还是Point 是多态基类?

    【讨论】:

      【解决方案3】:

      Parashift 对为什么禁止这样做有很好的解释:

      http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-15
        • 2013-07-24
        • 2011-05-17
        • 1970-01-01
        • 2011-11-10
        • 2011-01-06
        • 2020-05-08
        相关资源
        最近更新 更多