[实验任务一]:向量的原型
用C++完成数学中向量的封装,其中,用指针和动态申请支持向量长度的改变,使用浅克隆和深克隆复制向量类,比较这两种克隆方式的异同。
实验要求:
1. 画出对应的类图;
2. 提交源代码(用C+
完成);
#include "stdafx.h"
using namespace std;
class AbstractVector
{
public:
virtual AbstractVector* Clone() const = 0;
virtual void showData() = 0;
public:
double* len;//向量长度'
double begin;
double end;
};
class vector:public AbstractVector{
public: vector(double beg, double en){
begin = beg;
end = en;
len = new double;
if (end >= begin)
*len = end - begin;
else
*len = begin - end;
}
vector(const vector& cp){
int cho=0;
begin = cp.begin;
end = cp.end;
cout << "深克隆输入1,浅克隆选择2" << endl;
cin >> cho;
if (cho == 1){
len = new double;
*len = *(cp.len);
}
else
len = cp.len;
}
void showData(){
cout << "向量的长度为" << *len<<endl;
}
AbstractVector* Clone() const{
return new vector(*this);
}
~vector(){
delete len;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
AbstractVector* p = new vector(0,10);
AbstractVector* p1 = p->Clone();
cout << "p的长度为"; p->showData();
cout << "p1的长度为"; p1->showData();
if (p->len == p1->len){
cout << "这是浅克隆" << endl;
cout << "p->len的地址为" << p->len << endl;
cout << "p1->len的地址为" << p1->len << endl;
}
else{
cout << "这是深克隆" << endl;
cout << "p->len的地址为" << p->len << endl;
cout << "p1->len的地址为" << p1->len << endl;
}
system("pause");
return 0;
}
3.注意编程规范
标签:begin,end,cout,软件设计,double,len,vector From: https://www.cnblogs.com/renliqin/p/17857751.html