我想制作一个BlackJack游戏。
我想制作一个图像矢量,当我按下一个按钮时,会出现一个新图像(需要2或3个图像)。
之后我想在另一个按钮中删除所有这些按钮。
我尝试在主类(Unit1.h)中声明一个向量:
class TForm1 : public TForm{
...
public: TImage* Images[];
在Form1(Unit1.cpp)中:
void __fastcall TForm1::Button1Click(TObject *Sender)
{
// i=1 is global
Images[i] =new TImage(this);
Images[i]->Parent=this;
Images[i]->Picture->Bitmap->...//here i want to use it
i++;
}
在这里我想删除它们:
void __fastcall TForm1::Button3Click(TObject *Sender)
{
for(int k=1;k<=i;i++) {
Images[k]->~TImage(); //delete Images[k];
}
}
答案 0 :(得分:0)
您没有声明矢量。 std::vector
是C ++中的实际类类型。你实际声明的是一个未知大小的静态数组。你不能这样做。您必须在编译时为大小指定常量,例如:
class TForm1 : public TForm
{
...
public:
TImage* Images[3];
};
如果您在编译时不知道图像的数量,则必须将指针声明为在运行时动态分配的数组:
class TForm1 : public TForm
{
...
public:
TImage** Images;
int TotalNumberOfImages;
int NumberOfImages;
__fastcall TForm1(TComponent *Owner);
__fastcall ~TForm1();
};
__fastcall TForm1::TForm1(TComponent *Owner)
: TForm(Owner)
{
TotalNumberOfImages = ...;
Images = new TImage*[TotalNumberOfImages];
NumberOfImages = 0;
}
__fastcall TForm1::~TForm1()
{
delete[] Images;
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if (NumberOfImages < TotalNumberOfImage)
{
TImage *img = new TImage(this);
img->Parent = this;
img->Picture->...
...
Images[NumberOfImages++] = img;
}
}
void __fastcall TForm1::Button3Click(TObject *Sender)
{
for(int k = 0; k < NumberOfImages; ++k)
delete Images[k];
NumberOfImages = 0;
}
如果你真的想使用std::vector
,那么应该更像这样:
#include <vector>
class TForm1 : public TForm
{
...
public:
std::vector<TImage*> Images;
};
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TImage *img = new TImage(this);
img->Parent = this;
img->Picture->...
...
Images.push_back(img);
}
void __fastcall TForm1::Button3Click(TObject *Sender)
{
for(int k = 0; k < Images.size(); ++k)
delete Images[k];
/*
or:
for(std::vector<TImage*>::iterator iter = Images.begin(), end = Images.end(); iter != end; ++iter)
delete *iter;
*/
Images.clear();
}
或者,如果您使用的是Embarcadero基于Clang的C ++ 11编译器之一:
#include <vector>
#include <memory>
class TForm1 : public TForm
{
...
public:
std::vector<std::unique_ptr<TImage*>> Images;
};
void __fastcall TForm1::Button1Click(TObject *Sender)
{
std::unique_ptr<TImage> img(new TImage(this));
img->Parent = this;
img->Picture->...
...
Images.push_back(img);
}
void __fastcall TForm1::Button3Click(TObject *Sender)
{
Images.clear();
}