访问来自不同类的对象 - 设计
我有三个班,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
的附加价值,它没有带来任何功能。
我的建议是,其实很简单:
-
Image
类,以保存值 -
Processing
类(接口),应用操作 -
Encoder
和Decoder
类(接口),以读写不同格式
这对于确实有意义类,以便访问内部的图像只有当你可以从它那里得到的效率(这是有可能的),在这种情况下,你可以简单地让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
遵循相同的原则。
请注意,我从来不需要显式指针以及由此产生的保证正确性。
你的回复超过了我的预期。谢谢。你能解释一下如何在下面的语句中声明这个对象像素吗? std :: vector
@Raj:那么,什么是你的“像素”?你说你有一个像素矩阵,所以我想你会知道如何表示它们。典型代表包括RGB或YCMV等... – 2010-09-02 08:17:23
首先,根据您提供的代码,TImageProcessingEngine类中没有ReadImage()& WriteImage()函数,因此使用此类功能的后面的代码是有缺陷的。
至于解决,你可以做一个getter函数为tImageMatrix指针这样的:
tImageMatrix* GetImageMatrix() { return mpImageMatrix; }
然后,只需通过该指针(或指向整个的TImage实例)到你想要的TProcessing功能打电话。
我已声明TImage * mpImageProcessingEngine;在类TImageProcessingEngine中;所以我可以调用ReadImage()和WriteImage()方法。 – Raj 2010-09-01 08:08:41
,当它特别具有以下功能:只需访问mpImageMatrix;
在OOP中,你必须绑定的数据成员和它的操作 ..
因此,国际海事组织,删除你的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;
};
您应该尝试使用较少的'new'和较少的指针,并利用为值提供的自动清理。在删除它之后,设置一个指向'null'的指针也是不好的做法,它会隐藏错误。 – 2010-09-01 08:56:20
删除'隐藏错误'后将指针设置为NULL?恰恰相反,将其设置为NULL可确保在删除后指针的任何访问都会引发异常(在大多数C++编译器上授予:在所有用于x86的C++编译器上) – 2010-09-13 16:23:52