您的位置:首页 > 编程语言 > C语言/C++

C++智能指针,实现Mat类的复制控制

2016-10-24 13:10 791 查看
定义智能指针的通用技术是采用一个使用计数器。智能指针类将一个计数器与类指向的对象相关联。使用计数跟踪该类有多少个对象共享同一指针。当计数器为0时删除对象。使用计数有时也称为引用计数

//利用一个引用计数器控制复制和赋值构造函数,当引用计数器为零时,可以数据
//My_Image.h
#pragma once
#include <string>
namespace My_Code{
class Image_Data{
friend class My_Image;
Image_Data(const int& r, const int& m,  int** src);
~Image_Data();

int** data;
int rows;
int cols;
int use;                      //应用计数器
};

class My_Image
{
public:
~My_Image(void);
My_Image(const My_Image& src);
My_Image(int r, int c, int ** data);
My_Image& operator=(const My_Image& src);

My_Image& copyto(My_Image& src);
friend std::ostream&  operator<<(std::ostream &os, const My_Image& src);

private:
int get_rows() const { return image->rows;}
int get_cols() const { return image->cols;}
int** get_data() const{ return image->data;}
Image_Data* image;
};
}

//My_Image.cpp
#include "My_Image.h"
#include <iostream>

using namespace std;

namespace My_Code{
Image_Data::Image_Data(const int& r, const int& c,  int** src)
{
data = new int*[r];
for(int i=0; i<r; i++)
data[i] = new int[c];
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
data[i][j] = src[i][j];
rows = r;
cols = c;
use =1;
}

Image_Data::~Image_Data()
{
for(int i=0; i<rows; i++)
delete[] data[i];
delete[] data;
cout<<"destruct called"<<endl;
}

My_Image::My_Image(int r, int c, int ** data):image(new Image_Data(r, c, data)){ }

My_Image::My_Image(const My_Image& src){
image = src.image;
image->use++;
}

My_Image& My_Image::operator=(const My_Image& src)
{
if(--image->use ==0)
delete image;
image = src.image;
image->use++;
return *this;
}

ostream& operator<<(ostream &os, const My_Image& src){
for(int i=
945f
0; i<src.get_rows(); i++)
{
for(int j=0; j<src.get_cols(); j++)
os<<(src.get_data())[i][j] <<" ";
os<<endl;
}
return os;
}

//可以将一个图像的数据拷贝给另一个图像
My_Image& My_Image::copyto(My_Image& src)
{
if(--src.image->use==0)
delete src.image;
src.image = new Image_Data(get_rows(), get_cols(), image->data);
return src;

}

My_Image::~My_Image(void)
{
if(--image->use == 0)
delete image;
}
}

//main.cpp
#include <stdlib.h>
#include <iostream>
#include "My_Image.h"

using namespace std;
using namespace My_Code;

void main (void)
{
//生成一个int** 类型,作为二维数组参数
int ** data = new int*[2];
data[0] = new int[2*3];
for(int i=1; i<3; i++)
data[i] = data[i-1] + 2;

for(int i=0; i<2; i++)
for(int j=0; j<3; j++)
data[i][j] = i+j;

My_Image image1(2, 3, data);
My_Image * image2 = new My_Image(image1);
cout<<*image2;

for(int i=0; i<2; i++)
for(int j=0; j<3; j++)
data[i][j] = (i+j)*2;

My_Image  image3(2, 3, data);
image3.copyto(image1);

cout << image1 ;

system("pause");
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: