C++编译器如何用矢量构建动态对象

C++ Builder how to build dynamic Objects with vector?

本文关键字:构建 动态 对象 何用矢 编译器 C++      更新时间:2023-10-16

我正在C++Builder中开发IOS应用程序。我的问题是如何在for循环中构建TImage。我公开声明了矢量:

#include <vector>
std::vector<TImage*> Image(c); // public declaration 
void __fastcall TForm1::Button2Click(TObject *Sender)
{
 for (int i = 0; i < c ; i++){
    c = 5 // c should be send to te array
    Image[i] = new TImage(this); // I tried it this way but when i click the button i get an acess violence error
    Image[i]->Parent = BoardItem ;
    Image[i]->Height = 20 ; 
    Image[i]->Width = 20 ; 
   }
}

那么,如何使用向量在for循环中创建图像呢?

在C++Builder中动态定位一组图像我查找了这个问题的最后一个答案,但没有描述如何在循环中进行。

// c should be send to te array

如果更改变量c的值,它不会更改数组的大小。

您必须在Image向量上调用resize()才能更改大小,但这并不合适。最好写一些类似的东西

void TForm1::ClearImage() {
 for (int i = 0; i < Image.size(); ++i) {
     delete Image[i];
 }
 Image.clear();
}
void __fastcall TForm1::Button2Click(TObject *Sender)
{
 ClearImage();
 c=5;
 for (int i = 0; i < c ; i++){
    Image.push_back(new TImage(this));
    Image.back()->Parent = BoardItem ;
    Image.back()->Height = 20 ; 
    Image.back()->Width = 20 ; 
   }
}