根據題目的要求,下面將提供在 C++ 中 Image 類的成員函數 getpixel(), setpixel(), getwidth(), getheight() 的實現,以及一個 PrtImg() 函數來列印 Image 物件的圖元值。
首先是 Image 類的其他成員函數的實現:
cpp
Copy code
class Image {
private:
int width; // 寬
int height; // 高
unsigned char **pixel; // 圖元
public:
// 構造函數
Image(int w, int h) : width(w), height(h) {
pixel = new unsigned char*[height];
for (int i = 0; i < height; ++i) {
pixel[i] = new unsigned char[width];
}
}
// 解構函數
~Image() {
for (int i = 0; i < height; ++i) {
delete[] pixel[i];
}
delete[] pixel;
}
// 獲取圖元值
unsigned char getpixel(int r, int c) {
if (r >= 0 && r < height && c >= 0 && c < width) {
return pixel[r][c];
} else {
// 如果索引超出範圍,返回一個預設值
return 0;
}
}
// 設置圖元值
void setpixel(int r, int c, unsigned char g) {
if (r >= 0 && r < height && c >= 0 && c < width) {
pixel[r][c] = g;
}
}
// 獲取寬度
int getwidth() {
return width;
}
// 獲取高度
int getheight() {
return height;
}
};
接下來,實現 PrtImg() 函數:
cpp
Copy code
void PrtImg(Image &img) {
for (int i = 0; i < img.getheight(); ++i) {
for (int j = 0; j < img.getwidth(); ++j) {
std::cout << static_cast<int>(img.getpixel(i, j)) << " ";
}
std::cout << std::endl;
}
}
在 PrtImg() 函數中,通過兩層迴圈遍歷 Image 物件的 pixel 陣列。在內層迴圈中,列印每一行的圖元值,並用空格隔開。每列印完一行後,外層迴圈使得輸出換行,以開始新一行的列印。
請注意,這裡的 getpixel() 函數做了越界檢查,如果傳入的行號或列號超出了圖元陣列的範圍,函數會返回一個預設值(在這個例子中是 0)。同樣,在 setpixel() 函數中,也進行了越界檢查,以防止無效的記憶體訪問。當圖元值被列印時,由於 unsigned char 可能不會以數值形式列印,因此我們使用了 static_cast<int>() 來確保輸出為整數。