Joe*_*ams 54
你想要的是:
Foo *array[10]; // array of 10 Foo pointers
Run Code Online (Sandbox Code Playgroud)
不要混淆:
Foo (*array)[10]; // pointer to array of 10 Foos
Run Code Online (Sandbox Code Playgroud)
在任何一种情况下,都不会自动初始化任何内容,因为它们表示尚未分配给某些东西的Foos指针(例如,使用new).
当我意识到它描述了你如何访问基类型时,我终于在C中"得到"了指针/数组声明语法. Foo *array[5][10];意味着*array[0..4][0..9](5项的数组下标上,然后下标的10个项目,然后解除引用的指针阵列上)将访问Foo对象(注意,[]具有优先级高于*).
这似乎是倒退.你会认为int array[5][10];(aka int (array[5])[10];)是一个10的数组int array[5].假设是这种情况.然后你会通过说来访问数组的最后一个元素array[9][4].这不是倒退吗?因为C数组宣言是使用阵列不必被flipflopped指示如何获取到基型(而不是数组表达式的组合物等可以预期)的图案中,数组声明和代码.
例如,如果你想要一个int指针数组int* a[10].这意味着变量a是10 int*秒的集合.
编辑
我想这就是你想要做的:
class Bar
{
};
class Foo
{
public:
//Takes number of bar elements in the pointer array
Foo(int size_in);
~Foo();
void add(Bar& bar);
private:
//Pointer to bar array
Bar** m_pBarArr;
//Current fee bar index
int m_index;
};
Foo::Foo(int size_in) : m_index(0)
{
//Allocate memory for the array of bar pointers
m_pBarArr = new Bar*[size_in];
}
Foo::~Foo()
{
//Notice delete[] and not delete
delete[] m_pBarArr;
m_pBarArr = NULL;
}
void Foo::add(Bar &bar)
{
//Store the pointer into the array.
//This is dangerous, you are assuming that bar object
//is valid even when you try to use it
m_pBarArr[m_index++] = &bar;
}
Run Code Online (Sandbox Code Playgroud)