在 C++ 中的类定义中延迟数组大小?
有没有什么方法可以延迟定义数组的大小,直到类方法或构造函数?
我的想法可能看起来像这样,(当然)这是行不通的:
class Test
{
private:
int _array[][];
public:
Test::Test(int width, int height);
};
Test::Test(int width, int height)
{
_array[width][height];
}
Is there some way to delay defining the size of an array until a class method or constructor?
What I'm thinking of might look something like this, which (of course) doesn't work:
class Test
{
private:
int _array[][];
public:
Test::Test(int width, int height);
};
Test::Test(int width, int height)
{
_array[width][height];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Daniel 所说的是,当调用 Test (width, height) 方法时,您将需要动态地为数组分配内存。
您将像这样声明二维(假设整数数组):
然后在您的测试方法中,您需要首先分配指针数组,然后为每个指针分配一个整数数组:
然后当释放对象时您将需要显式删除您分配的内存。
What Daniel is talking about is that you will need to allocate memory for your array dynamically when your Test (width, height) method is called.
You would declare your two dimensional like this (assuming array of integers):
And then in your Test method you would need to first allocate the array of pointers, and then for each pointer allocate an array of integers:
And then when the object is released you will need to explicit delete the memory you allocated.
矢量是你最好的朋友
vector is your best friend
我认为您是时候查找新的/删除的运算符了。
由于这是一个多维数组,因此您必须在调用“new”时循环调用(再次不要忘记:删除)。
尽管我确信很多人会建议使用具有宽度*高度元素的一维数组。
I think it is time for you to look up the new/delete operators.
Seeing as this is a multidimensional array, you're going to have to loop through calling 'new' as you go (and again not to forget: delete).
Although I am sure many will suggest to use a one-dimensional array with width*height elements.
(几个月后)人们可以使用模板,如下所示:
(Months later) one can use templates, like this: