将单例类型定义为成员变量

typedef singleton as member variable

本文关键字:成员 变量 定义 单例 类型      更新时间:2023-10-16

试图访问下面的成员变量s,导致以下错误:

错误:'cl::s{也称为单例}'不是'cl'的基

class singleton
{
public:
static singleton* getInstance()
{
  static singleton* ptr{nullptr};
  if(nullptr==ptr)
  {
    ptr=new singleton;
  }
  return ptr;
}
private:
  int m_var;
};
class cl
{
public:
   typedef singleton s;
};
int main() 
{
  cl* c;
  c->s::getInstance();
}

我没想到会出现这种错误。我做错了什么?

不能通过实例访问类型名。写:

cl::s::getInstance();

c++将c->s::getInstance()解释为对c所指向的对象调用s::getInstance的尝试。在基类上调用覆盖(或隐藏)的成员函数,或消除从多个基类继承的成员函数的歧义时,可以使用此语法:

struct A { void foo(); };
struct B: A { void foo(); };
B b;
b.foo();     // calls B::foo
b.A::foo();  // calls A::foo