문제

Trying to access the member variable s below, results in the following error:

error: 'cl::s {aka singleton}' is not a base of '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();
}

I wasn't expecting an error of this sort. What am I doing wrong?

도움이 되었습니까?

해결책

You can't access type names through an instance. Write:

cl::s::getInstance();

C++ is interpreting c->s::getInstance() as an attempt to call s::getInstance on the object pointed to by c. You can use this syntax when calling overridden (or hidden) member functions on a base class, or disambiguating member functions inherited from multiple base classes:

struct A { void foo(); };
struct B: A { void foo(); };
B b;
b.foo();     // calls B::foo
b.A::foo();  // calls A::foo
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top