简体   繁体   中英

C++ making an array of pointers to const objects

I'm trying to make a non-constant array of non-constant pointers to constant objects. The idea is that I should be able to change what the pointers in the array point to, but what they point to is a constant object.

I'm having problem defining this array (it's an array of pointers to objects of type Person - a custom class). I'm currently declaring the array like so:

Person* people[10];

Also that's not explicitly saying that the pointers point to const Persons. So when I do something like this:

people[i] = &p;

where p is a reference to an object of type const Person , it fails.

When in doubt ... use typedef (because it's explicit, adds more specialized semantics and avoids the confusion completely):

typedef const Person* PersonCPtr;
PersonCPtr people[10];

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