分配另一类类型的新数组值

assigning a new array values of another class type

本文关键字:新数组 数组 一类 分配 类型      更新时间:2023-10-16

基本上,我试图制作一个派生类的动态数组,基类与另一个类具有组合关系。

这是我使用的课程

class Album:public PhotoLab{
public:
Album(string);
Album(Image* ,string);
~Album();
void newProject(); //This is the function I'm working on
.
.
private:
string title;
string* names;
};

类PhotoLab包含

class PhotoLab{
public:
PhotoLab();
PhotoLab(Image*);
PhotoLab(Image*, int);
virtual  ~PhotoLab();
.
.
virtual void newProject()=0;
protected:
Image* I;
int Num;
 virtual void trans()=0;};

和图像类

class Image{
public:
// Image();
 Image(string="");
 ~Image();
.
.
 void load(string);
.
.
private:
 string magicNo;
 int H, W, colorSystem;
 RGB** pixels;
 string ID;};

回到我试图制作I的动态数组的类相册,这是我正在使用的函数:

void Album::newProject(){
 cout<<"Number of images: ";
cin>>Num;
names=new string [Num];
for(int i =0;i<Num;i++){
    cout<<"Image("<<i+1<<") Name: ";
    cin>>names[i];}
    I=new Image[Num];
    for (int i=0;i<Num;i++){
        I[i]=new Image(names[i]);} // I got An error here when I tried to make and object of class Image?? 

我在这里搞什么,为什么错了?

在函数中,您使用的是变量I,它是一个Images数组(您使用new[]以这种方式创建它)。然后,您可以获得are的索引,该索引的类型为Image。这是一个错误,您使用新操作符创建了一个新的Image,但此操作符返回一个Image*。编译器无法将Image*转换为Image,因此会给您一个错误。

解决此问题的最简单方法是将I声明为指向Images的指针数组。

Image** I;

然后在你的方法中创建一个图像指针数组:

I = new Image*[num];
for(int i = 0; i < num; i++)
{
    I[i] = new Image(names[i]);
}

您正在尝试为类类型分配指针。

试试这个:

  1. PhotoLab中的Image* I;更改为Image** I;
  2. Album::newProject()中的I=new Image[Num];更改为I=new Image*[Num];

您的I对象显然是Image[],即Image对象的数组。

当您newImage时,您将得到一个指向Image指针。您正试图将Image(即I[i])设置为包含Image*

建议:多态容器应该真正存储一些对实际对象的引用类型,即unique_ptr<Image>可能是最好的。

另一个建议是:除非你(非常)有经验或有(大量)时间调试内存问题,否则不要使用C风格的数组。改为使用std::vector

std::vector<std::unique_ptr<Image>> I;
for (int i=0; i!=Num; ++i) {
    I.push_back( std::make_unique<Image>(names[i]) );
}

但是!

可能您甚至不需要多态容器I:然后使用简单的std::vector<Image>

std::vector<Image> I;
...
for( int i=0; i != Num; ++i) {
    I.emplace_back( names[i] ); // will construct an Image in place
}