类可以定义在某个函数的内部,这样的类被称为局部类(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'
-
相关阅读:
node分布式(小鹿线)
网络编程头文件与数据结构
OJ练习第177题——打家劫舍 IV(二分查找)
【后端速成 Vue】初识指令(下)
新大陆!阿里 P9 整理出:Java 架构师“成长笔记”共计 23 版块
解决MySQL需要根据特定顺序排序
[C++入门]---List的使用及模拟实现
Hive Lateral View explode列为空时导致数据异常丢失
Nacos Config
win10安装及配置Gradle
-
原文地址:https://blog.csdn.net/qfturauyls/article/details/126438715