【发布时间】:2012-12-24 02:13:56
【问题描述】:
我有一个尴尬的问题。我认为这是不可能的,但我需要确定。这有点奇怪,但我需要我的子类共享父类的 SAME Pixels 向量。
基本上,我想创建一个 Image 类的实例。该 Image 类将保存 Bitmap 和 Png 类的像素,因此如果我需要从 Bitmap 转换为 PNG,反之亦然,它们使用相同的矢量,而不是我创建 Bitmap 和 PNG 类。
class Image
{
private:
std::vector<RGB> Pixels;
};
class Bitmap : Image
{
public:
Bitmap() : Image() {};
};
class Png : Image
{
public:
Png() : Image() {};
};
这样当我这样做时:
int main()
{
Image Img();
Img.GetBitmapPixels(); //This
Img.GetPngPixels(); //And this, return the same Pixels Vector.
Bitmap Foo = Img.ToPng();
Png Moo = Img.ToBitmap();
//Such that both Foo and Moo have the exact same underlying Pixels Vector.
}
目前我的课程如下:
class Bitmap
{
private:
std::vector<RGB> Pixels;
public:
Bitmap();
std::vector<RGB> GetPixels() {return Pixels;}
void SetPixels(std::vector<RGB> Pixels) {this->Pixels = Pixels;}
};
class Png
{
private:
std::vector<RGB> Pixels;
public:
Png();
std::vector<RGB> GetPixels() {return Pixels;}
void SetPixels(std::vector<RGB> Pixels) {this->Pixels = Pixels;}
};
要从一种转换到另一种,我必须这样做:
int main()
{
Bitmap Bmp();
Png PNG();
PNG.SetPixels(BMP.GetPixels); //BMP has to COPY PNG's Pixels and vice-versa..
}
这是一个愚蠢的问题。我只是不想复制像素。我只是希望能够在两个类之间进行转换而无需任何复制,因为这两个类都拥有一个 std::vector Pixels 成员并且数据对齐相同。
我想我正在努力做到:PNG.SaveAsBitmap(...);或 BMP.SaveAsPNG(...);而不创建另一个的新实例。
如何避免复制/创建和创建要转换到的其他类的新实例?我可以拥有相互继承的类吗?
【问题讨论】:
-
为什么要将图像类分成两个单独的类?为什么不将像素存储为原始位图,然后当您需要加载/保存时,它会有不同的方法来加载/保存 PNG、JPG、BMP 等。
-
好吧,因为它们相当大并且已经正常运行。我不想打破它并合并它们。他们也有同名的成员做完全不同的事情。我不确定你的意思是将像素存储为原始位图。它们是两个不同的类:S 原始像素存储在该向量中。
-
我在两种不同类型的图像类中看不到重点。您在两个类中都有一个
RGB数组,为什么要将共性分为两个不同的类。加载图像后,您可以将其存储为带有 RAW 像素数据的通用格式(这就是我所说的位图)。我要做的是:有一个代表通用图像的Image类。有一个ImageLoader和ImagerSaver类来加载和保存图像,具体取决于您希望加载/保存的文件格式。 -
我会这样做的。我将制作一个通用的 Image 类。我写的时候没有考虑到这一点:l
标签: c++