单例模式

[实验任务一]:学号的单一

仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。

实验要求:

1. 画出对应的类图;

 

2.提交源代码;

#include<iostream>

#include<string>

using namespace std;

 

class StudentNo

{

private:

 

static StudentNo  *student;

string no;

StudentNo() {};

 

 

void setStudentNo(string no1)

{

no = no1;

}

 

public:

 

static StudentNo  * getStudent() {

if (student == NULL) {

cout << "第一次分配学号, 分配新学号!" << endl;

student = new StudentNo();

student->setStudentNo("20194023");

}

else {

cout << "学号已存在,获取旧学号!" << endl;

}

return student;

}

 

string getStudentNo() {

return no;

}

 

};

 

StudentNo * StudentNo::student = NULL;  //初始化 student

 

int main() {

StudentNo * no1, *no2;

no1 = StudentNo::getStudent();

no2 = StudentNo::getStudent();

cout << "学号是否一致:" << (no1 == no2) << endl;

 

string str1, str2;

str1 = no1->getStudentNo();

str2 = no2->getStudentNo();

cout << "第一次学号" << str1 << endl;

cout << "第二次学号" << str2 << endl;

cout << "内容是否相等" << (!str1.compare(str2)) << endl;   //str1 == str2 时值为0

cout << "是否相同对象" << (str1 == str2) << endl;

}

3. 注意编程规范。

 

 

posted @ 2021-10-06 20:53  Zwyooo  阅读(35)  评论(0编辑  收藏  举报