原型模式

[实验任务一]:向量的原型

C++完成数学中向量的封装,其中,用指针和动态申请支持向量长度的改变,使用浅克隆和深克隆复制向量类,比较这两种克隆方式的异同。

实验要求:

1. 画出对应的类图;

 

 

 

2.提交源代码(用C++完成);

#include<iostream>

#include<math.h>

using namespace std;

//深克隆类

class vectorDeep

{

private:

double *x1;

double *y1;

double *x2;

double *y2;

public:

vectorDeep(double i1, double j1, double i2, double j2)

{

cout << "构造函数(深克隆类)(" << i1 << "," << j1 << ")(" << i2 << "," << j2 << ")" << endl;

x1 = new double(i1);

y1 = new double(j1);

x2 = new double(i2);

y2 = new double(j2);

}

vectorDeep(const vectorDeep &P)

{

cout << "拷贝构造函数" << endl;

x1 = new double(*P.x1);

y1 = new double(*P.y1);

x2 = new double(*P.x2);

y2 = new double(*P.y2);

}

~vectorDeep() {

cout << "析构函数(深克隆类)" << endl;

delete x1;

delete y1;

delete x2;

delete y2;

}

void display()

{

cout << "向量长度:";

double ans = sqrt(pow((*x1 - *x2), 2) + pow((*y1 - *y2), 2));

cout << ans << endl;

}

};

//浅克隆类

class vectorShallow

{

private:

double *m1;

double *n1;

double *m2;

double *n2;

public:

vectorShallow(double i1, double j1, double i2, double j2)

{

//动态内存分配并赋值

cout << "构造函数(浅克隆类)(" << i1 << "," << j1 << ")(" << i2 << "," << j2 << ")" << endl;

m1 = new double(i1);

n1 = new double(j1);

m2 = new double(i2);

n2 = new double(j2);

}

~vectorShallow() {

cout << "析构函数(浅克隆类)" << endl;

delete m1;

delete n1;

delete m2;

delete n2;

}

void display()

{

cout << "向量长度:";

double ans = sqrt(pow((*m1 - *m2), 2) + pow((*n1 - *n2), 2));

cout << ans << endl;

}

};

int main() {

double i = 1.0, j = 1.0;

double m = 4.0, n = 5.0;

cout << "选择克隆模式:1.浅克隆 2.深克隆:";

cin >> n;

if (n == 1) {

vectorShallow v0(i, j, m, n);

vectorShallow v1 = v0;

cout << "原类输出:";

v0.display();

cout << "浅克隆类输出:";

v1.display();

}

else if (n == 2) {

vectorDeep v0(i, j, m, n);

vectorDeep v1 = v0;

cout << "原类输出:";

v0.display();

cout << "深克隆类输出:";

v1.display();

}

else {

cout << "输入错误!" << endl;

}

return 0;

}

2. 注意编程规范。

 

 

 

posted @ 2021-10-04 23:17  Zwyooo  阅读(34)  评论(0编辑  收藏  举报