[英]Accessing an object from a different class - Design
我有三個類, TImageProcessingEngine
, TImage
和TProcessing
TImageProcessingEngine
是我用來將我所有方法公開的工具。
我打算使用TImage
來使用通用圖像讀取和圖像寫入功能。
TProcessing
包含將執行映像操作的方法。
class TImageProcessingEngine
{
public:
TImage* mpImageProcessingEngine;
};
class TImage
{
public:
int ReadImage();
int WriteImage();
private:
//a two dimensional array holding the pixel values
tImageMatrix* mpImageMatrix;
};
class TProcessing
{
public:
int ConvertToBinary();
int ConvertToGrayScale();
};
我的問題是如何訪問對象mpImageMatrix
類TProcessing
? 這樣我的調用應用程序可以使用以下內容
TImageProcessingEngine* vEngine = new TImageProcessingEngine;
//Converts an input gray scsale image to binary image
vEngine->ReadImage().ConvertToBinary();
//Write the converted image to disk
vEngine->WriteImage();
delete vEngine;
vEngine = NULL;
//During this whole processing internally,
//the image is read in to `mpImageMatrix`
//and will also be holding the binarised image data,
//till writing the image to disk.
還是您對我的課堂設計推薦其他方法?
首先,根據您提供的代碼,TImageProcessingEngine類中沒有ReadImage()和WriteImage()函數,因此在以后使用此類功能的代碼中存在缺陷。
對於解決方案,您可以為tImageMatrix指針創建一個getter函數,如下所示:
tImageMatrix* GetImageMatrix() { return mpImageMatrix; }
然后,只需將該指針(或指向整個TImage實例的指針)傳遞給要調用的TProcessing函數即可。
為什么要有一個單獨的TProcessing
進程,當它專門具有僅訪問mpImageMatrix;
功能時mpImageMatrix;
在OOP中,您必須綁定 數據成員及其操作 ..
因此,IMO,刪除您的TProcessing
類,並在TImage
具有這兩個功能。
您的TImage
就像
class TImage
{
public:
int ReadImage();
int WriteImage();
int ConvertToBinary();
int ConvertToGrayScale();
private:
//a two dimensional array holding the pixel values
tImageMatrix* mpImageMatrix;
};
我當然會推薦其他實現,但是讓我們先檢查一下設計。
我不太了解TImageProcessingEngine
,它沒有帶來任何功能。
我的建議實際上非常簡單:
Image
類,用於保存值 Processing
類(接口),以應用操作 Encoder
和Decoder
類(接口),用於讀寫不同的格式 僅當您可以從中獲得效率時, Processing
類才可以訪問內部圖像(這很有可能),這是有意義的,在這種情況下,您可以簡單地與Processing
成為朋友,並對其進行解包以獲取其派生值。
class Image
{
public:
Image();
void Accept(Processing& p);
void Encode(Encoder& e) const; // Image is not modified by encoding
void Decode(Decoder& d); // This actually resets the image content
private:
friend class Processing;
size_t mHeight;
size_t mWidth;
std::vector<Pixel> mPixels; // 2D array of Pixels
};
class Processing
{
public:
void apply(Image& image)
{
this->applyImpl(image.mHeight, image.mWidth, image.mPixels);
}
private:
virtual void applyImpl(size_t h, size_t w, std::vector<Pixel>& pixels) = 0;
};
Encoder
和Decoder
遵循相同的原理。
請注意,我永遠不需要顯式指針,以及由此產生的保證正確性。
您可以創建一個訪問器TImage
類:
byte * pixelAt(unsigned x, unsigned y);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.