【发布时间】:2021-03-17 10:15:19
【问题描述】:
我从一位前同事那里继承了一个项目,我发现了这些代码 sn-ps(以及 SO questions 中的一些类似代码:can a c++ class include itself as an member 和 static member object of a class in the same class)
// Service.h
class Service
{
// ...
public:
static Service sInstance;
void Somememberfunc();
//...
};
// Service.cpp
#include "Service.h"
Service Service::sInstance;
void Service::Somememberfunc()
{
//...
}
// Main.cpp
#include "Service.h"
void Fun()
{
Service &instance = Service::sInstance;
//...
instance.Somememberfunc();
//...
}
但是,我没有找到关于何时使用此模式的任何解释。又有哪些优点和缺点?
【问题讨论】: