C++ 单例与多态继承

对于单例而言,只能有一个实例。
对于多态而言,可能有多个实例。
为了在多态中运用单例的思想,可以这样写。

//base.h
class BASE {
  public:
    static BASE& GetInstance(const int type);
    BASE() = default;
    virtual ~BASE() = default;
};
//base.cpp
#include "base.h"
#include "derived.h"
BASE& BASE::GetInstance(const int type) {
  if (type == "0") {
    static Base A;
    return A;
  } else {
    static Derived B;
    return Derived;
}

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部