原型模式--C++实现

发布时间 2023-11-02 12:32:51作者: yesyes1

浅克隆

#include<iostream>
#include<algorithm>

using namespace std;

//计算类
class Compute {
public:
	int* p;
	int len;//向量长度
	Compute(int len);
	Compute(const Compute &compute);//构造函数
	~Compute();//析构函数
	int operator[](int i) const {
		return p[i];
	}

	int& operator[](int i) {
		return p[i];
	}

	int length()const {
		return len;
	}
};

//各种函数的实现
Compute::Compute(int len) :len(len) {
	p = (int*)calloc(len, sizeof(int));
}

Compute::Compute(const Compute& compute) {
	this->len = compute.len;
	//this->p = (int*)calloc(len, sizeof(int));
	//memcpy(this->p, compute.p, len * sizeof(int));

	this->p = compute.p;
}

Compute::~Compute() {
	free(p);
}

void display(const Compute &compute) {
	int len = compute.length();
	for (int i = 0; i < len; i++) {
		if (i == len - 1) {
			cout << compute[i] << endl;
		}
		else {
			cout << compute[i] << " ,";
		}
	}
}



int main() {
	Compute c1(10);
	for (int i = 0; i < 10; i++) {
		c1[i] = i;
	}

	Compute c2 = c1;//浅克隆

	c1[7] = 3;
	c1[4] = 6;

	cout << "浅克隆:" << endl;

	cout << "c1的数据:" << endl;
	display(c1);

	cout << "c2的数据:" << endl;
	display(c2);

	return 0;
}

深克隆

#include<iostream>
#include<algorithm>

using namespace std;

//计算类
class Compute {
public:
	int* p;
	int len;//向量长度
	Compute(int len);
	Compute(const Compute &compute);//构造函数
	~Compute();//析构函数
	int operator[](int i) const {
		return p[i];
	}

	int& operator[](int i) {
		return p[i];
	}

	int length()const {
		return len;
	}
};

//各种函数的实现
Compute::Compute(int len) :len(len) {
	p = (int*)calloc(len, sizeof(int));
}

Compute::Compute(const Compute& compute) {
	this->len = compute.len;
	this->p = (int*)calloc(len, sizeof(int));
	memcpy(this->p, compute.p, len * sizeof(int));
}

Compute::~Compute() {
	free(p);
}

void display(const Compute &compute) {
	int len = compute.length();
	for (int i = 0; i < len; i++) {
		if (i == len - 1) {
			cout << compute[i] << endl;
		}
		else {
			cout << compute[i] << " ,";
		}
	}
}



int main() {
	Compute c1(10);
	for (int i = 0; i < 10; i++) {
		c1[i] = i;
	}

	Compute c2 = c1;//深克隆

	c1[7] = 3;
	c1[4] = 6;

	cout << "深克隆:" << endl;

	cout << "c1的数据:" << endl;
	display(c1);

	cout << "c2的数据:" << endl;
	display(c2);

	return 0;
}