内嵌类有两种类型:内联(inner)类和静态内嵌(static nested)类。
c++嵌套类等同于内部类的概念,定义嵌套类的目的是为了隐藏信息,提高代码的抽象能力,相当与在内部为外部类提供了一种新的类型。
查阅了相关资料,发现内嵌类有两种类型:内联(inner)类和静态内嵌(static nested)类。但是经过个人测试并没有太大差异,所以现将使用方法及注意要点作出总结如下。
1.内嵌类可以访问定义在外围类(enclosing class)中的静态实例变量。外围类不可以访问嵌套类的私有成员.
看下面这段代码:
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
class Singleton
{
public:
static Singleton* GetInstance() {
// 注意这里一定要使用Double-Check的方式加锁,才能保证效率和线程安全
if (nullptr == m_pInstance) {
m_mtx.lock();
if (nullptr == m_pInstance) {
m_pInstance = new Singleton();
}
m_mtx.unlock();
}
return m_pInstance;
}
// 实现一个内嵌垃圾回收类
class CGarbo {
public:
~CGarbo(){
if (Singleton::m_pInstance)
delete Singleton::m_pInstance;
}
};
// 定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数从而释放单例对象
static CGarbo Garbo;
private:
// 构造函数私有
Singleton(){};
// 防拷贝
Singleton(Singleton const&);
Singleton& operator=(Singleton const&);
static Singleton* m_pInstance; // 单例对象指针
static mutex m_mtx; //互斥锁
};
Singleton* Singleton::m_pInstance = nullptr;
Singleton::CGarbo Garbo;
mutex Singleton::m_mtx;
这是之前提到过的单例模式中的“懒汉模式”;
我们在Singletion中内嵌了一个“垃圾回收类”;定义一个静态成员变量(回收类的对象),程序结束时,系统会自动调用它的析构函数从而释放单例对象。
2.不能从内嵌类中访问外部类的非静态成员.
错误的访问方式:
加上static修饰后:
3.可以在外部通过作用域限定符调用.
//静态嵌套类的测试
#include<iostream>
#include<windows.h>
using namespace std;
class outer
{
public:
static class inner
{
public:
inner(int a) :_in(a)
{
cout << "你好世界" << endl;
}
int _in;
};
private:
static int _a;
};
int outer::_a = 2;
void func()
{
//通过类+作用域限定符创建对象
outer::inner in(5);
cout << in._in;
}
int main()
{
func();
system("pause");
return 0;
}
测试结果:
个人总结,评论区欢迎补充讨论。