原型模式
作者:互联网
浅克隆:
#include <iostream> #include <string.h> #include <stdlib.h> using namespace std; class vector{ private: char *name; int len; public: int *p; bool changeLength1D(int *&a,int oldLength, int newLength) { if(newLength < 0){ printf("输入有误!数组长度不能为负!"); return false; } int* temp = new int[newLength]; int number = std::min(oldLength, newLength); std::copy(a, a+number, temp); delete [] a; a = temp; return true; } vector(const char *Name,int Len)//构造函数 { name=new char[strlen(Name)+1]; strcpy(name,Name); len=Len; p = new int[len]; for(int i=0;i<len;i++){ p[i] = i; } cout<<"construct ..."<<endl; } ~vector() { cout<<"destruct ..."<<len<<endl; delete name; } void dispaly() { cout<<"name:"<<name<<" len:"<<len<<endl; } void setLen(int x) { len=x; } }; int main() { int oldlen = 2,newlen = 6; vector v("1",oldlen); if(v.changeLength1D(v.p,oldlen,newlen)){ v.setLen(newlen); } for(int i=2;i<6;i++) v.p[i]=i; for(int i=0;i<6;i++) cout << v.p[i] << endl; vector v2 = v; for(int i=0;i<6;i++) cout << v2.p[i] << endl; return 0; }View Code
深克隆:
#include <iostream> #include <string.h> #include <stdlib.h> using namespace std; class vector{ private: char *name; int len; public: int *p; bool changeLength1D(int *&a,int oldLength, int newLength) { if(newLength < 0){ printf("输入有误!数组长度不能为负!"); return false; } int* temp = new int[newLength]; int number = std::min(oldLength, newLength); std::copy(a, a+number, temp); delete [] a; a = temp; return true; } vector(const char *Name,int Len)//构造函数 { name=new char[strlen(Name)+1]; strcpy(name,Name); len=Len; p = new int[len]; for(int i=0;i<len;i++){ p[i] = i; } cout<<"construct ..."<<endl; } vector(const vector &v)//拷贝构造函数 { name=new char[strlen(v.name)+1]; strcpy(name,v.name); len=v.len; p = v.p; cout<<"copy construct ..."<<endl; } ~vector() { cout<<"destruct ..."<<len<<endl; delete name; } void dispaly() { cout<<"name:"<<name<<" len:"<<len<<endl; } void setLen(int x) { len=x; } }; int main() { int oldlen = 2,newlen = 6; vector v("1",oldlen); if(v.changeLength1D(v.p,oldlen,newlen)){ v.setLen(newlen); } for(int i=2;i<6;i++) v.p[i]=i; for(int i=0;i<6;i++) cout << v.p[i] << endl; vector v2 = v; for(int i=0;i<6;i++) cout << v2.p[i] << endl; return 0; }View Code
标签:Name,newLength,int,模式,char,原型,new,include 来源: https://www.cnblogs.com/wangzhaojun1670/p/13899745.html