C++ detailed parsing of nested and local classes

  • 2020-04-02 01:31:23
  • OfStack

1. The nested class
The peripheral class needs to use the nested class object as the underlying implementation, and the nested class is only used for the implementation of the peripheral class, while hiding the underlying implementation from the user.
From a scope perspective, nested classes are hidden in peripheral classes, and their names can only be used in peripheral classes. If you use the class name in a scope outside the peripheral class, you need to qualify the name.

A member function in a nested class can be defined outside of its class.

Nested class member functions have no access to private members of the peripheral class, and vice versa.

Nested classes are only syntactically embedded.

2. The local class
Classes can also be defined in the body of a function, and such classes are called local classes (loacl classes). A local class is only visible in the local field where it is defined.

The member functions of a local class must be defined in the class body.

You cannot have static member functions in a local class.

In practice, local classes are rarely used.

Here is a piece of code to illustrate:


#include<iostream>
using namespace std;
class Outer
{
public:
 class Inner
 {
 public:
  void Fun();
 };
public:
    Inner obj_;
 void Fun()
 {
   cout<<"Outer::Fun...."<<endl;
   obj_.Fun();
 }
};
void Outer::Inner::Fun()
{
  cout<<"Inner::Fun..."<<endl;
}
void Fun()
{
  class LocalClass
  {
  public:
   int num_;
   void Init(int num)
   {
     num_=num;
   }
   void Display()
   {
     cout<<"num_"<<num_<<endl;
   }
  };
  LocalClass lc;
  lc.Init(10);
  lc.Display();
}
int main()
{
  Outer o;
  o.Fun();
  Outer::Inner i;
  i.Fun();
  Fun();
  return 0;
}

Operation results:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201309/201309120859584.jpg ">


Related articles: