类构造函数及赋值操作符重载解析

#include<stdlib.h>

#include<string.h>

class image

{

public:

image();          //默认构造函数

image(int _height, int _width, int _channal);//带参数构造函数

~image(); //析构函数

image(const image& other);//拷贝构造函数

image& operator=(const image& other);//赋值操作符重载

private:

int height; //私有成员

int width;

int channal;

unsigned char *data;

};

image::image()

{

height = 0;

width = 0;

channal = 0;

data = NULL;

}

image::image(int _height, int _width, int _channal)

{

height = _height;

width = _width;

channal = _channal;

int total = height*width*channal;

data = new unsigned char[total]();

}

image::image(const image& other)

{

height = other.height;

width = other.width;

channal = other.channal;

int total = height*width*channal;

data = new unsigned char[total](); //深拷贝

memcpy(data, other.data, sizeof(unsigned char)*total);

}

image& image::operator=(const image& other)

{

height = other.height;

width = other.width;

channal = other.channal;

int total = height*width*channal;

if (data)    //清除原有存储空间

delete[] data;

data = new unsigned char[total]();//重分配存储空间,深拷贝

memcpy(data, other.data, sizeof(unsigned char)*total);

return *this;

}

image::~image()

{

if (data)

delete[] data;

}

image test(image tmp) //测试拷贝构造函数,输入时会调用拷贝构造函数初始化形参tmp

{                  //return时会调用拷贝构造函数初始化一个临时image对象

return tmp;

}

int main()

{

image a; //调用默认构造函数

image b(32, 32, 3);//调用带参数构造函数,初始化32*32的三通道图像,初始值都为0

a = b;//调用赋值操作符重载函数,深拷贝

image c = b;//调用拷贝构造函数,深拷贝

image d(b); //调用拷贝构造函数

a = test(b);//return时的临时image对象再用赋值操作符重载给a

image e = test(b);//return时的临时image对象无需再用拷贝构造函数初始e

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容