1. 构造函数为私有
2. 对象指针是类的静态成员
class people {
private:
std::string name;
int age;
static people *instance;
public:
static people* getInstance() {
if (instance == nullptr) {
instance = new people("11", 10);
static huishou c1;
}
return instance;
}
class huishou {
public:
~huishou() {
std::cout << "析构" << std::endl;
if (instance) {
delete instance;
instance = nullptr;
}
}
};
int getAge() {
return age;
}
std::string getName() {
return name;
}
private:
people(std::string p_name, int p_age) {
std::cout << "构造" << std::endl;
name = p_name;
age = p_age;
}
public:
~people() {
}
};
people* people::instance = nullptr; //静态成员变量在类外初始化
int main()
{
{
std::cout << people::getInstance()->getName() << std::endl;
std::cout << people::getInstance()->getAge() << std::endl;
}
return 0;
}