简体   繁体   中英

Invalid conversion from int** to const int**

I have a class with a 2D array of ints implemented as an int**. I implemented an accessor function to this 2D array as follows, returning a const int** to prevent the user from being able to edit it:

const int** Class::Access() const
{
     return pp_array;
}

But I got the compilation error "invalid conversion from int** to const int**". Why is a promotion to const not allowed here? How can I give the user access to the information without editing rights?

Greyson is correct that you'll want to use const int* const* , but didn't explain why your original version failed.

Here is a demonstration of why int** is incompatible with const int** :

const int ci = 0;
const int* pci = &ci;
int* pi;
int** ppi = π
const int** ppci = ppi; // this line is the lynchpin
*ppci = pci;
*pi = 1; // modifies ci!

I was mistaken about the const ness of the method being the reason for the error. As Ben points out, the const -ness of the method is irrelavent, since that applies only to the value of the exterior pointer [to pointers to int s], which can be copied to a mutable version trivially.

In order to protect the data (which is your preferred outcome) you should make both the int s and the pointers to int s constant:

int const * const * Class::Access() const
{
   return pp_array;
}

Will work.

If you prefer to have the const in front you can also write the declaration like so:

const int * const * Class::Access() const;

but since the second const applies to the pointers, it must be placed to the right (like the const which applies to the method) of the asterisk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM