类可以定义在某个函数的内部,这样的类被称为局部类(local class)。 注意是定义而不是声明,这就意味着在函数内部声明这个类的同时就要进行实现,换句话说,局部类的所有数据成员和成员函数必须定义在类的内部。
- #include
- using namespace std;
-
- class A {
- public:
- int a;
- static int cnt;
- void fun1() {cout<<"A::fun1"<
- void f()
- {
- //局部类
- class Local{
- public:
- int x;
- void fun2() {
- cout<<"Local::fun2,cnt="<
- /*编译error:error: use of non-static data member 'a' of 'A' from nested type 'Local'*/
-
- //cout<<"Local::fun2,x="<
- /*error: reference to local variable 'x' declared in enclosing function 'A::f'*/
-
- }
- void fun3();
-
- //局部嵌套类
- class LocalInner{
- public:
- int c;
- void fun4()
- {
- cout<<"LocalInner::fun4,c="<
- }
- };
- };
- }
- };
-
- //编译error: no member named 'Local' in 'A',因为:局部类必须定义(即实现)在函数的内部,不能在函数外部实现。
- // void A::Local::fun3() {
- // cout<<"Local::fun3"<
- // }
-
- void test_fun() {
- //Local d; //编译error:error: unknown type name 'Local',因为:局部类定义的类型只在定义它的作用域内可见,即局部类只在定义它的函数内部有效,在函数外部无法访问局部类。
- A a;
- a.f();
- }
-
- int main()
- {
-
- test_fun();
- return 0;
- }
说明:
- Local是局部类,定义在类A的f()成员函数中;
- LocalInner是局部嵌套类,定义在局部类Local中;
- fun2和fun3是局部类Local的成员函数,必须在声明的同时进行定义;
- Local可以访问外部类A的静态数据成员cnt,不可以访问类A的非静态数据成员a,如下:
//cout<<"Local::fun2,a="<
-
Local局部类不能使用函数作用域中的变量,即下面的代码会发生编译错误:
- cout<<"Local::fun2,x="<
- 编译错误:error: reference to local variable 'x' declared in enclosing function 'A::f'
-
相关阅读:
上周热点回顾(1.8-1.14)
【CLI命令行接口和Java连接openLooKeng查询数据 】
[LeetCode周赛复盘] 第 321 场周赛20221127
虾皮插件能做数据分析的-知虾数据分析插件Shopee大数据分析平台
阿里云服务器系统怎么选?Alibaba Cloud Linux操作系统介绍
【C进阶】之动态内存分配及内存操作函数
计算机操作系统 第五章 虚拟存储器(1)
展开说说:Android Fragment完全解析-卷一
大开眼界,Jenkins 结合 SpringCloud+K8S,打通微服一条龙技术讲解
程序编码风格要求
-
原文地址:https://blog.csdn.net/qfturauyls/article/details/126438715