我有一個問題,下面的代碼(編譯器沒有抱怨,但我在運行時得到一個錯誤消息 - R6010中止)。基本上我創建了一個Image類,它從圖像中讀取數據並將其存儲在動態分配的數組中。然後我想要將圖像數據傳入int main中的另一個數組。出於某種原因,這是行不通的。C++從動態數組返回值(圖像類)
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;
}
謝謝!這完全是問題所在。非常感謝幫助我 – elrim