软件设计——单例模式之学生唯一学号C++

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、运行截图

原文地址:https://www.cnblogs.com/ltw222/p/15368068.html