Nested class and department class in C ++
Nesting class and department class in C ++
I recently took advantage of my free time during the Spring Festival holiday and learned several chapters on C ++ Primer. I found that many features in C ++ are unknown to me. The Nested classes and department classes are quite useful and simple to write about their usage.
Nested class
A nested class can define another class in one class. The scope of the nested class is only in its upper-level class. The following is an example:
#include <iostream>using namespace std;class c1{public: int a; void foo(); class c2 { public: int a; void foo(); } b;};void c1::foo(){ a = 1;}void c1::c2::foo(){ a = 2;}int main(){ class c1 f; f.foo(); f.b.foo(); cout << f.a << endl; cout << f.b.a << endl; return 0;}
In fact, the C language also has a similar usage, nesting another struct in a struct, or embedding a union in a struct. We also know that the nested structure or union in C is usually anonymous. It is also possible in C ++. We can nest another anonymous class in a class. However, the member functions of an anonymous class can only be defined at the same time in the class declaration. Because this class has no name, we cannot refer to it externally.
The following is a similar example:
class c3{public: int a; void foo() {a = 3;} class { public: int a; void foo() {a = 4;} } b;};int main(){ class c3 ff; ff.foo(); ff.b.foo(); cout << ff.a << endl; cout << ff.b.a << endl; return 0;}
Local class
A local class is a class defined within a function. This class can only be used within the function. The following is an example:
int main(){ class c4 { public: int a; void foo() {a = 4;} }; class c4 ff; ff.foo(); cout << ff.a << endl; return 0;}
Generally, all member variables of the nested class and department class are declared as common. Because these two types are only used in a small range, it is not necessary to use the defined interface to hide internal information. Therefore, you can change the class to struct, so that you do not need to write public.
In addition, a function cannot be nested. For example, the following example cannot be compiled.
int main(){ void foo() { cout << "WRONG";}; foo();}
However, we can simulate a local function through some flexible methods. Specifically, a function call is simulated by reloading the operator () method of a class. The following is an example:
int main(){ struct { void operator () ( void ) { cout << "HELLO" << endl; } int operator() (int a, int b) { return a + b; } } foo; foo(); cout << foo(1, 2);}