问题
I want to make a game of BlackJack.
I want to make a vector of images and when I press a button a new image shows up(need 2 or 3 images).
After that I want to delete all of them in another button press.
I try to declare an vector in main class(Unit1.h):
class TForm1 : public TForm{
...
public: TImage* Images[];
And in 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++;
}
And here i want to delete them:
void __fastcall TForm1::Button3Click(TObject *Sender)
{
for(int k=1;k<=i;i++) {
Images[k]->~TImage(); //delete Images[k];
}
}
回答1:
You did not declare a vector. std::vector is an actual class type in C++. What you actually declared is a static array of unknown size. You cannot do that. You must specify a constant for the size at compile-time, eg:
class TForm1 : public TForm
{
...
public:
TImage* Images[3];
};
If you do not know the number of images at compile-time, you must declare a pointer to an array that is dynamically allocated at runtime instead:
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;
}
If you really want to use a std::vector
, it should be more like this instead:
#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();
}
Or, if you are using one of Embarcadero's Clang-based C++11 compilers:
#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();
}
来源:https://stackoverflow.com/questions/34141850/dynamic-alocation-an-array-of-images-in-c-builder