gpt4 book ai didi

C++ 从动态数组返回值(图像类)

转载 作者:行者123 更新时间:2023-11-27 23:15:38 24 4
gpt4 key购买 nike

我遇到以下代码的问题(编译器没有提示,但我在运行时收到一条错误消息 - R6010 中止)。基本上我创建了一个 Image 类,它从图像中读取数据并将其存储在动态分配的数组中。然后我想将图像数据传递到 int main 中的另一个数组。由于某种原因,这不起作用。

class Image
{
private:
char* charImage;
int TotRows;
int TotCol;
int Size;
int MaxVal;
char Magic[2];

public:
Image();
Image (const Image& Orig);
~Image();
void operator=(const Image&); //overloaded assignment operator
void ReadImage();
char ReturnImage(int i);
int getSize();
};

Image::Image()//constructor
{
Size = (3 * TotRows * TotCol);
charImage = new char [Size];
}

Image::Image (const Image& Orig)//copy constructor
{
TotRows = Orig.TotRows;
TotCol = Orig.TotCol;
Size = Orig.Size;
charImage = new char [Size];
}

Image::~Image()//destructor
{

delete []charImage;
}

void Image::operator=(const Image& Orig)
{
TotRows = Orig.TotRows;
TotCol = Orig.TotCol;
Size = Orig.Size;
charImage = new char [Size];

for (int i = 0; i < Size; i++)
{
charImage[i]=Orig.charImage[i];
}
}

void Image::ReadImage()
{
//opening original image
ifstream OldImage;
OldImage.open ("image2.ppm", ios::in | ios::binary);

if (!OldImage)
cout << "\nError: Cannot open image file! " << endl;

//reading the header of the original image file
OldImage >> Magic [0] >> Magic [1];

//if the image is not in the right format, do not proceed!
if ((Magic [0] != 'P')||(Magic [1] != '6'))
cout << "\nError: image is in the wrong format!" << endl;

else
OldImage >> TotRows >> TotCol >> MaxVal;

//reading the image in binary format and storing it in the array of characters
OldImage.read(charImage, Size);

}

char Image::ReturnImage(int i)
{
return charImage[i];
}
int Image::getSize()
{
return Size;
}

int main ()
{
char* charImage;
int Size;
Image myImage;
myImage.ReadImage();
Size = myImage.getSize();

charImage= new char [Size];

for (int i=0; i<Size; i++)
{
charImage[i]=myImage.ReturnImage(i);
}

delete [] charImage;

return 0;
}

最佳答案

一个明显的错误是您没有在默认构造函数中设置图像的尺寸:

Image::Image()//constructor
{
Size = (3 * TotRows * TotCol);
charImage = new char [Size];
}

此处,TotRowsTotCol 未初始化,可以具有任何值。

然后,在赋值运算符中,在使 charImage 指向一个新数组之前,您没有释放它指向的数组,因此您正在泄漏资源。

关于C++ 从动态数组返回值(图像类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16563895/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com