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;
}
版权声明:本文为fengruoying93原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。