[实验任务一]:向量的原型
用C++完成数学中向量的封装,其中,用指针和动态申请支持向量长度的改变,使用浅克隆和深克隆复制向量类,比较这两种克隆方式的异同。
#include <iostream> using namespace std; //向量类 class Vector{ private:int *p;int len; public:Vector(int len);Vector(const Vector &vector); //拷贝构造函数~Vector();int operator[](int i) const { return p[i]; }int &operator[](int i){ return p[i]; }int length() const { return len; } }; Vector::Vector(int len): len(len){p = (int*)calloc( len, sizeof(int) ); } //拷贝构造函数 Vector::Vector(const Vector &vector){this->len = vector.len;this->p = vector.p; } Vector::~Vector(){ free(p); } //打印 void display(const Vector &vector){int len = vector.length();for(int i=0; i<len; i++){if(i == len-1){cout<<vector[i]<<endl;}else{cout<<vector[i]<<", ";}} } int main(){Vector v1(10);for(int i=0; i<10; i++){v1[i] = i;}Vector v2 = v1;v2[6] = 55;v2[2] = 20;cout<<"浅克隆:"<<endl;cout<<"更改copyVector后vector的数据:"<<endl;display(v1);cout<<"更改copyVector后copyVector的数据:"<<endl;display(v2);return 0; }
[实验任务一]:学号的单一
仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。
#include<iostream> #include<string> #include <string.h> using namespace std; //单例角色——StudentNo类 class StudentNo{ private:static StudentNo* instance;string no;StudentNo(){}void setStudentNo(string n){no=n;} public:static StudentNo* getInstance(){if(instance==NULL){cout<<"第一次注册,分配新的学号"<<endl;instance=new StudentNo();instance->setStudentNo("20203935");}else{cout<<"重复注册,获取旧的学号"<<endl;}return instance;}string getStudentNo(){return no;} }; StudentNo* StudentNo::instance=NULL; int main(){StudentNo *x,*y;x=StudentNo::getInstance();y=StudentNo::getInstance();cout<<"学号是否一致";if(x==y){cout<<"true"<<endl;}string a,b;a=x->getStudentNo();b=y->getStudentNo();cout<<"第一次学号是"<<a<<endl;cout<<"第二次学号是"<<b<<endl;cout<<"内容是否相等";if(strcmp(a.c_str(),b.c_str())==0){cout<<"true"<<endl;}cout<<"是否是相同对象";if(a==b){cout<<"true"<<endl;}return 0; }