18.6 local class
Classes can be defined within the function body. Such classes are called local classes ). A local class defines a type, which is only visible in the local scope that defines it. Different from Nested classes, local class members are strictly restricted.
All the members (including functions) of a local class must be fully defined within the class definition body. Therefore, local classes are far less useful than Nested classes.
Similarly, local classes are not allowed to declare static data members and there is no way to define them.
1. Local classes cannot use variables in the function Scope
The names of peripheral scopes that can be accessed by local classes are limited. A local class can only access type names, static variables, and enumeration members defined in the peripheral scope, and cannot use variables in functions that define this class.
[Cpp] int;
Class TheClass3 {
Public:
Void foo (int c)
{
Static int si;
Enum Loc {e = 1024, f };
Class Bar {
Public:
Loc locVal;
Int barVal;
Void fooBar (Loc I = e)
{
BarVal =:;
BarVal = si;
BarVal = f;
}
};
}
};
Int;
Class TheClass3 {
Public:
Void foo (int c)
{
Static int si;
Enum Loc {e = 1024, f };
Class Bar {
Public:
Loc locVal;
Int barVal;
Void fooBar (Loc I = e)
{
BarVal =:;
BarVal = si;
BarVal = f;
}
};
}
};
2. General protection rules apply to local classes
Peripheral functions do not have special access to private members of local departments. Of course, local classes can set peripheral functions as friends.
In fact, private Members in a local class are almost unnecessary. Generally, all members of a local class are public members.
3. Search for names in a local class
4. nested local classes
A class can be nested inside a local class. In this case, the nested class definition can appear outside the local class definition body, but the nested class must be defined in the same scope that defines the local class. Generally, the name of the nested class must be limited by the name of the peripheral class, and the declaration of the nested class must appear in the definition of the local class.
[Cpp] class TheClass3 {
Public:
Void foo ()
{
Class Bar {
Class NestedBar;
};
Class Bar: NestedBar {
};
}
};
From xufei96's column