嵌套类是定义在类内部的类,嵌套类可以访问外部类的私有成员:
#define debug qDebug()<<
class outside
{
public:
explicit outside(int f,int s):frist{f},second{s}
{
}
static int four;
private:
int frist;
int second;
class inside
{
public:
void fun(outside*c)
{
debug c->frist;//访问私有成员
debug c->second;
debug c->four;//访问static成员
debug this->three;
}
private:
int three{8888};
};
public:
inside innerObject;
};
int outside::four = 666;
int main(int argc, char *argv[])
{
outside a(1,2);
a.innerObject.fun(&a);
}
外部类不能访问嵌套类的私有成员:
嵌套类的一个常用的用法是用于单例模式销毁对象:
class A
{
public:
static A* getInstance();
private:
explicit A()
{
debug "A构造";
};
~A(){};
static A* instance;
class B
{
public:
~B()
{
if(A::instance)
delete A::instance;
}
};
static B b;
};
A* A::instance;
A* A::getInstance()
{
if (!instance)
{
instance = new A();
}
return instance;
}
int main(int argc, char *argv[])
{
A::getInstance();
}
单例模式的对象不像如果不清除它,对象会一直存在,使用静态的嵌套类对象可以清除单例对象。这里类A使用单例模式,A中定义一个嵌套类的静态对象b,静态对象保存在静态存储区。在程序结束时,它就会被销毁,系统会调用它的析构函数,在析构函数里清除类A的单例对象。