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

#include

#include

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

}

你可能感兴趣的:(类构造函数及赋值操作符重载解析)