#include<stdlib.h>
#include<string.h>
class image
{
public:
image();? ? ? ? ? //默認(rèn)構(gòu)造函數(shù)
image(int _height, int _width, int _channal);//帶參數(shù)構(gòu)造函數(shù)
~image(); //析構(gòu)函數(shù)
image(const image& other);//拷貝構(gòu)造函數(shù)
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)? ? //清除原有存儲(chǔ)空間
delete[] data;
data = new unsigned char[total]();//重分配存儲(chǔ)空間橙依,深拷貝
memcpy(data, other.data, sizeof(unsigned char)*total);
return *this;
}
image::~image()
{
if (data)
delete[] data;
}
image test(image tmp) //測(cè)試拷貝構(gòu)造函數(shù),輸入時(shí)會(huì)調(diào)用拷貝構(gòu)造函數(shù)初始化形參tmp
{? ? ? ? ? ? ? ? ? //return時(shí)會(huì)調(diào)用拷貝構(gòu)造函數(shù)初始化一個(gè)臨時(shí)image對(duì)象
return tmp;
}
int main()
{
image a; //調(diào)用默認(rèn)構(gòu)造函數(shù)
image b(32, 32, 3);//調(diào)用帶參數(shù)構(gòu)造函數(shù)颇象,初始化32*32的三通道圖像蕴掏,初始值都為0
a = b;//調(diào)用賦值操作符重載函數(shù)讶坯,深拷貝
image c = b;//調(diào)用拷貝構(gòu)造函數(shù)休建,深拷貝
image d(b); //調(diào)用拷貝構(gòu)造函數(shù)
a = test(b);//return時(shí)的臨時(shí)image對(duì)象再用賦值操作符重載給a
image e = test(b);//return時(shí)的臨時(shí)image對(duì)象無(wú)需再用拷貝構(gòu)造函數(shù)初始e
}