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

assigning a new array values of another class type

基本上我正在尝试创建一个派生的动态数组 class,其中基础 class 与另一个 class.

具有组成关系

这是我正在使用的 classes

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;
};

class 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

class Image{
public:
// Image();
 Image(string="");
 ~Image();
.
.

 void load(string);
.
.
private:
 string magicNo;
 int H, W, colorSystem;
 RGB** pixels;
 string ID;};

返回 class 专辑,我正在尝试制作 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?? 

我在这里搞砸了为什么那是错的?

您正在尝试将指针分配给 class 类型。

试试这个:

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

在您的函数中,您正在使用变量 I,它是一个图像数组(您使用 new[] 以这种方式创建它)。然后你会得到一个索引到那个区域,然后它的类型是 Image。这是错误,您使用 new 运算符创建了一个新图像,但是这个运算符 returns 是一个 Image*。编译器无法将 Image* 转换为 Image,因此会报错。

解决这个问题的最简单方法是将 I 声明为指向图像的指针数组。

Image** I;

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

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

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

当您 new 一个 Image 时,您将得到一个 指向 一个 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
}