在你的情况下,w
和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));
}
}
从我的图像处理经验,考虑将图像作为一个单一的表,行由行。你可以通过调用data[y * w + x];
在这种情况下访问(X,Y)个元素,可以简化您的拷贝构造函数:
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
}
如果需要的分配状的方法,一些图像中的哪拷贝内容(无论是存储在一个无符号整型*或在另一个图像类)到图像的现有例如,w
和h
不能常量。
'好像......',不幸的是,这种说法是错误的。任何构造函数都不需要删除已有的构造函数,因为所有构造函数都以未初始化的对象开始。你的问题是别的。张贴更多的代码。 – john 2013-04-24 08:38:30
这段代码是完全错误的。 'image'将永远是一个无效的指针,你会尝试删除那些不存在的东西。 – Gorpik 2013-04-24 08:42:03
这是一个复制构造函数? :) – 2013-04-24 08:43:01