C++ instance的使用

fengruoying93發表於2020-10-08

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 *get_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::get_instance()->set_student(18, "alex");
	Student::get_instance()->show();
	Student::get_instance()->destroy_instance();
	
	return 0;
}

 

相關文章