我编写了一个从文件中读取Image
(2-d数组)并返回它的函数。
调用它给了我一个Block-Type错误,我可以通过删除析构函数来抑制它 我的错误在哪里?我甚至需要一个析构函数吗?
#include <vector>
#include <stdio.h>
#include <conio.h>
#include <iostream>
#include <fstream>
using namespace std;
struct Pixel {
float p;
};
class Image {
int _x, _y;
Pixel *pix;
public:
Image(int x, int y) {
pix = new Pixel[x * y];
_x = x;
_y = y;
}
~Image() {
delete[] pix;
pix = NULL;
}
Image& operator= (const Image& param) {
_x = param._x;
_y = param._y;
pix = new Pixel[_x*_y];
pix = param.pix;
return *this;
}
float getPixel(int i, int j) {
return pix[(i-1) * _y + (j-1)].p;
}
void setPixel(int i,int j, Pixel val) {
pix[(i-1) * _y + j-1].p = val.p;
}
Pixel **GetData() {
Pixel **a=0;
a = new Pixel*[_x];
for (int i = 0; i < _x; i++) {
a[i] = new Pixel[_y];
for (int j = 0; j < _y; j++)
a[i][j] = pix[i*_y + j];
}
return a;
}
};
Image ReadFromFile(string a) {
FILE * pFile;
const char * c = a.c_str();
Pixel pix,**tval;
int n,m;
pFile=fopen(c,"r");
fscanf(pFile, "%i %i", &n, &m);
Image img(n, m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
fscanf(pFile, "%f", &pix.p);
img.setPixel(i, j, pix);
}
fclose(pFile);
return img;
}
int main(){
// Example Usage
Image img(10, 10);
Image img2(3, 3);
Pixel val[10][10], **tval;
for (int row = 1; row <= 10; row++)
for (int col = 1; col <= 10; col++) {
val[row-1][col-1].p = 2*row + col;
img.setPixel(row, col, val[row-1][col-1]);
}
for (int row = 1; row <= 10; row++) {
for (int col = 1; col <= 10; col++)
cout << img.getPixel(row,col) << ' ';
cout << '\n';
}
cout << '\n';
tval = img.GetData();
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++)
cout << tval[row][col].p << ' ';
cout << '\n';
}
string a;
a = "C:/programs/misha/out.txt";
img2 = ReadFromFile(a);
cout << '\n';
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++)
cout << img2.getPixel(row+1, col+1) << ' ';
cout << '\n';
}
}