C++ instance单例模式

    科技2025-11-12  5

    1、test.h

    #pragma once #include <string> class Student { public: Student(); Student(int age, std::string name); virtual ~Student(); static int create_instance(); static void destroy_instance(); static Student *instance() { return m_instance; } void set_student(int age, std::string name); void show(); private: int m_age; std::string m_name; private: static Student* m_instance; };

    2、test.cpp

    #include "test.h" #include <iostream> #include <string> using namespace std; Student *Student::m_instance = NULL; Student::Student() { m_age = 0; } Student::Student(int age, std::string name) : m_age(age), m_name(name) { } Student::~Student() { cout << "bye." << endl; } int Student::create_instance() { Student::m_instance = new Student; if(NULL != m_instance) return 0; else return -1; } void Student::destroy_instance() { if(m_instance) { delete m_instance; m_instance = NULL; } } void Student::show() { cout << "age:" << m_age << " name:" << m_name << endl; } void Student::set_student(int age, std::string name) { m_age = age; m_name = name; }

    3、main.cpp

    #include <iostream> #include <string> #include <vector> #include "test.h" using namespace std; int main(void) { Student::create_instance(); Student::instance()->set_student(18, "alex"); Student::instance()->show(); Student::instance()->destroy_instance(); return 0; }

     

    Processed: 0.009, SQL: 8