嵌套类

嵌套类是定义在类内部的类,嵌套类可以访问外部类的私有成员:

#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的单例对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值