在您的情况下,作为 constw
并没有错。h
您可以通过以下方式编写构造函数:
MyImage(unsigned int** _image,unsigned int _w,unsigned int _h)
: w(_w), h(_h)
{
// No data is allocated in the memory pointed to by image yet
// We have to allocate it here. Remember, that copy-ctor is
// a constructor, so it operates on newly created instance,
// not on an existing one.
image = new unsigned int * [h];
for (int i = 0; i < h; i++)
{
image[i] = new unsigned int [w];
memcpy(image[i], _image[h], w * sizeof(unsigned int));
}
}
根据我的图像处理经验,考虑将图像逐行存储为单个表。您可以通过调用访问 (x, y)-th 元素data[y * w + x];
在这种情况下,您可以简化您的复制 ctor:
MyImage::MyImage(unsigned int * source, int newW, int newH)
: w(newW), h(newH)
{
image = new unsigned int[w * h];
memcpy((void *)image, (void *)source, w * h * sizeof(unsigned int));
}
按照 C++ 社区对这个术语的理解,复制构造函数看起来像这样:
MyImage::MyImage(const MyImage &source)
: w(source.w), h(source.h)
{
image = new unsigned int[w * h];
memcpy((void *)image, (void *)source.image, w * h * sizeof(unsigned int));
}
请注意,当您调用构造函数时该image
字段不存在,因此您不需要释放任何内容。
// Your code
MyImage(unsigned int** _image,unsigned int _w,unsigned int _h)
{
// Class is allocated into some part of memory, which might
// have been used, so in effect this may be actually true,
// because image may contain some rubbish data
if (image)
{
// But this will result mostly likely in Access Violation
// error, because you would try to use (free!) some random
// data in memory.
for (int i = 0;i < w;++i)
delete[] image[i];
delete[] image;
}
// .. copy _image to imge
}
如果您需要类似分配的方法,它将某些图像的内容(存储在 unsigned int * 或另一个 Image 类中)复制到现有的 Image 实例,w
并且h
不能是 const。