[实验任务一]:学号的单一
仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。
#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; }
标签:学号,no,模式,StudentNo,static,C++,单例,include From: https://www.cnblogs.com/rongzhang/p/16773889.html