Why am I getting an error converting a ‘float**’ to ‘const float**’?

前端 未结 4 2087
旧巷少年郎
旧巷少年郎 2020-11-29 07:26

I have a function that receives float** as an argument, and I tried to change it to take const float**.

The compiler (g++) did

4条回答
  •  遥遥无期
    2020-11-29 07:44

    Other anwers have detailled why this is an error in C++.

    Let me address the question behind your question. You wanted to state, in the interface of your function, that your function will not modify float values contained in the array. Nice intention, and enables that your function is called with const float ** arrays. The question behind your question would be, how to achieve this without resolving to ugly casts.

    The correct way to achieve what you wanted is to change the type of your function parameter to const float * const *.

    The additional const between the stars assures the compiler that your method will not try to store pointers to const float in the array, since this type declares that the pointer values are also const.

    You can now call this function with float ** (which was the example in your question), const float **, and const float * const * arguments.

提交回复
热议问题