分配另一类类型的新数组值
assigning a new array values of another class type
基本上,我试图制作一个派生类的动态数组,基类与另一个类具有组合关系。
这是我使用的课程
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]);
}
您正在尝试为类类型分配指针。
试试这个:
- 将
PhotoLab
中的Image* I;
更改为Image** I;
- 将
Album::newProject()
中的I=new Image[Num];
更改为I=new Image*[Num];
您的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
}
相关文章:
- 新的整数数组向右移动?
- 标量"新 T "与数组"新 T[1]"
- 如何将标准::字符串内容克隆到新的 char[] 数组
- C++ strcpy_s复制到新的字符数组时引发错误
- 无限数组C++在一个表达式中使用两个新值调整数组大小
- 新动态字符数组末尾的空字符
- c ++新的C数组分配,RAII或简单的shared_ptr/boost::shared_array
- 返回新分配的数组
- 数组的末尾指向新分配的数组C++
- 如何创建新的字符串数组
- 动态数组:将中两个动态数组中元素的值添加到新的动态数组中
- 一组数组添加到一个新数组
- 将新值写入数组
- 按值传递字符数组,并从函数返回一个新的字符数组
- 用不同的指定值初始化新的c++数组
- [C++]在此代码之前不存在的析构函数中引发的内存错误。尝试创建一个新的动态数组并填充它
- 动态分配一个新的整数数组
- 将两个字符串的相似性写入新的动态数组的最简单方法
- 如何在C++中动态创建新的 2D 数组
- 分配新的布尔数组指针