C ++数组的指针 [英] C++ Array Of Pointers

查看:131
本文介绍了C ++数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,如果我想要一个指针数组,这样我可以有他们指向不同的对象在后期是什么语法样子。

In C++ if I want an array of pointers so that I may have them point to different objects at a latter stage what does the syntax look like.

修改

我要澄清什么,我试图做我猜。我有了和添加方法的类Foo。在add方法我把上课条的引用。我想保存到参考条的指针数组。指针栏的阵列将需要这一切我有没有问题的时候进行扩展。它是对指针的堆创建和阵列,这样我以后可能会分配栏对象给他们。我曾尝试似乎级栏不具有该编译器抱怨默认构造函数失败。这使我认为,我是创造和我不想做实际的对象数组。

I need to clarify what I am trying to do I guess. I have a class foo that has and add method. In the add method I take a reference to class bar. I want to save that reference into a pointer array of bar. The array of pointer bar will need to be expanded all the time this I have no problems with. It is creating and array on the heap of pointers so that I may assign bar objects to them later. What I have tried seems to fail as class bar does not have a default constructor which the compiler is complaining about. This lead me to think that I was creating and array of actual objects which I did not want to do.

请没有STL,没有我不想听你是如何认为这是疯狂等就是你的意见。

Please no stl and no I do not want to hear about how you think this is crazy etc that is your opinion.

推荐答案

你想要的是:

Foo *array[10]; // array of 10 Foo pointers

不要与困惑:

Foo (*array)[10]; // pointer to array of 10 Foos

在这两种情况下,没有什么会被自动初始化,因为这些重新present指针,尚未被分配到的东西FOOS(例如用新)。

In either case, nothing will be automatically initialized because these represent pointers to Foos that have yet to be assigned to something (e.g. with new).

我终于当我意识到它描述了如何访问基型C得到指针/数组声明的语法。 富*阵列[5] [10]; 表示 *数组[0..4] [0..9] (共5项的数组下标,那么下标10项的数组,然后解引用一个指针)将访问Foo对象(注意, [] 有更高的precedence比 * )。

I finally "got" pointer/array declaration syntax in C when I realized that it describes how you access the base type. Foo *array[5][10]; means that *array[0..4][0..9] (subscript on an array of 5 items, then subscript on an array of 10 items, then dereference as a pointer) will access a Foo object (note that [] has higher precedence than *).

这似乎倒退。你可能会认为 int数组[5] [10]; (又名 INT(数组[5])[10]; )为10 int数组的数组[5] 。假如是这样的话。那么你会说访问数组的最后一个元素阵列[9] [4] 。难道这不是向后看吗?由于C数组声明使用数组指示如何去的基本类型(而不是阵列前pressions的组成像人们所预料的)的模式,数组声明和code不必被flipflopped

This seems backwards. You would think that int array[5][10]; (a.k.a. int (array[5])[10];) is an array of 10 int array[5]. Suppose this were the case. Then you would access the last element of the array by saying array[9][4]. Doesn't that look backwards too? Because a C array declaration is a pattern indicating how to get to the base type (rather than a composition of array expressions like one might expect), array declarations and code using arrays don't have to be flipflopped.

这篇关于C ++数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆