C + + Internal classes

Source: Internet
Author: User

1. When a member variable of an external class is not a type name, static, or enumerator, the inner class cannot use the member variable directly, such as:

classylbase{ Public:    enumEnum_futures_model{continuetwelve =0, Onefivenine =1}; stringm; /**********************************************************date class*************************************** *****************/    classDate {Private:        intYear ; intmonth; intDay ; /*************private method****************/        voidAddoneday ();//Added 1 days        voidSuboneday ();//1 days Reduced        intSubsmalldate (ConstDate &date)Const;//subtract a smaller Date and return the number of days     Public:        /**********************construction****************************/Date (); Date (intYearintMonthintDay ); ~date (void); /*************is bool***********************/        //bool Isstandforyear;//True Date contains the year of month (0) Day (0)//bool Isstandformonth;//true Date contains year Month day (0)//bool Isstandforday;//true:date contains year month day        /*************get Set method****************/        voidSetDate (intYearintMonthintDay ); intgetYear (); intGetMonth (); intGetDay (); voidSetyear (intiyear); voidSetmonth (intimonth); voidSetday (intiday); /*************public method****************/        intDaysPerMonth (intm=-1)Const;//How many days per month?         intDaysperyear (inty=-1)Const;//How many days per year?         intCompareConstDate &date)Const;//similar to compare in string, returns equal to 0        BOOLIsleapyear (inty=-1)Const;//whether a leap year        intSubdate (ConstDate &date)Const;//subtract a date and return the number of daysDate Subdays (intDaysConst;//reduce the number of days specifiedDate AddDays (intDaysConst;//increase the number of days specified        stringtoString (); /********** Operator Overloading ***********/Date&operator++();//+ + DateDateoperator++(int);//Date + +date&operator--();//--DateDateoperator--(int);//Date--Dateoperator+(intDays);//Date + DaysDateoperator-(intDays);//date-days        int operator-(ConstDate &date);//Date1-date2        BOOL operator< (Constdate& d)Const; BOOL operator()(Constdate& D1,Constdate& D2)Const; BOOL operator== (Constdate& d)Const; };

Ylbase is an external class date for an inner class that can use the Enum_futures_model defined directly in date ylbase, but cannot use m directly. To use the member variables of an external class directly in the inner class, refer to the following code

classOutclass { Public:      intm; classInclass//the inner class accesses members of the external class through the parent pointer, including public, private    {       Public:          voidSet_m (inti) {outclass*parent = (Outclass *) ((Char*) This-Offsetof (Outclass,inch)); Parent->m =i; }      }inch;    }; voidMain () {outclass out;  out.inch. Set_m (123); cout<< out. M <<Endl; System ("Pause"); } 

Summarize:

Although the inner class is defined inside the outer category, it is a separate class that is essentially unrelated to the outer class. Its members are not part of an external class, and similarly, members of the outer class do not belong to that inner class. The appearance of an inner class simply tells the external class that there is one such type member for use by an external class. Also, the external class has no privileges for access to internal class members, and the internal classes access to the external class members as well, and they all follow the label access control that the ordinary class has.

If a member is not defined inside an inner class, its definition can only be written to the same scope as the outer class, and it must be qualified with an outer class, and the definition cannot be written in an external class. For example, a static member of an inner class is one such example.

2. Benefits of the Inner class

Inner class is a nested class (n e t s t e D C L a s s)
One of them. Like other members of a class, nested classes can also be declared as static or
Non-static. A static nested class, also known as a top-level nested class (t o p-l e v e l n e s T e DC L a s s), is a non-static nested class called an inner class (i n n e r C L a s s). Static nested classes
Just provides a convenient way to organize code, similar to the name NULL in C + +
Room The most important type of a nested class is an inner class.
An inner class object can access the contents of the external class object that created it, and the package
is a very useful feature for system design, providing a more
A lot of ideas and methods. To implement this feature, the inner class object must have a reference to the
A reference to an external class object. J a v A compiler when creating an inner class object, implicitly
The reference to its external class object is also passed in and kept. This will make
An internal class object can always access its outer class object, and that is why
Outside the scope of the outer class to create an inner class object must first be created
The reason for the partial object.
In C + + to simulate the implementation of the internal class mechanism, the need for the use of C + ten nested
Class. At the same time, an object in the inner class needs to hold an argument for its enclosing class object
or pointers, and, in order for an inner class object to be able to access the outer class object's
Private variables and methods require that the inner class be declared as a friend of the outer class. Specific
The implementation methods and usage scenarios are as follows:

#include <iostream>
#include <string>
using namespace Std;
Interface Lanibi
struct Iambi
{
virtual void Ambi () = 0;
};
Interface ipingable
struct Ipingable:public iambi{
virtual void ping () = 0;
virtual void Ambi () = 0;
}
Interface ipangable
struct Ipangable:public iambi{
Virtualvoidpang () = 0;
Virtualvoidambi () = 0;
};
void Callping (Ipingable & P) {
P.PMG ();
P.ambi ();
}
void Callpang (Ipangable & B) {
B.pang);
B.ambi ();
}
Class Pingpang:public ipingable{
Private variables enclosing the class Pingpang
String content_private;
Declares an inner class inner and declares it as a friend of the Pingpang class
Class Inner;
Friend class Inner;
Class inner:publicipangable(
The inner class holds a pointer or reference to its enclosing class
Pingpang*parent;
Public
Inner (pingpang*p):p arent (p) {}
The inner class can access the private variable that encloses the class (here is Content_private)
void Pang () {
cout<< "Pangcalledforinnerof ' <<parent->content-private<<end
}
The signature of this virtual function is the same as its enclosing class, and there is no name ambiguity in order to rewrite it independently
void Ambi () (
cout<< "Ambicalledforinner" <<endl;
}inner;
Public
Pingpang (const string& str): Content_private (str) Iinner (this) {}
void Ping () (cout<< "Pingcalledforouter" <<endl;)
void Ambi () (cout<< "Ambicalledforouter" <<endl;)
Returns a reference to an interface ipangable implemented by an inner class
Operator ipangable& () {returninner;)
);
int main (intargc,char*argv[])
{
Pingpang x ("Pingpang");
/The effect here is similar to upcast the Pingpang class to two base classes
Callping (x);
Callpang (x);
return 0;
}

C + + Internal classes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.