单例模式

#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("20191111");
        }
        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;
}

 

posted @ 2021-10-06 21:15  yasai  阅读(27)  评论(0编辑  收藏  举报