简体   繁体   English

C ++创建一个指向const对象的指针数组

[英]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). 我在定义这个数组时遇到了问题(它是一个指向Person类型对象的指针数组 - 一个自定义类)。 I'm currently declaring the array like so: 我目前正在声明这样的数组:

Person* people[10];

Also that's not explicitly saying that the pointers point to const Persons. 还没有明确说明指针指向const人。 So when I do something like this: 所以当我做这样的事情时:

people[i] = &p;

where p is a reference to an object of type const Person , it fails. 其中p是对const Person类型的对象的引用,它失败了。

When in doubt ... use typedef (because it's explicit, adds more specialized semantics and avoids the confusion completely): 如果有疑问...使用typedef(因为它是显式的,添加更专业的语义并完全避免混淆):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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