Chapter 14

xiaoxiao2021-03-06  14

Chapter 14

This chapter describes C classes, classes introduced user-defined types in the program, and class can contain data and functions.

The user-defined type in the traditional programming language is the collection of data. They are placed together to describe the properties and status of the object. Class types in C enable users not only describe the properties and status of the object, but also define the behavior of the object.

This chapter includes some topics below:

* Overview of class

* Class name

* Class member

* Member function

* Static data member

* United

* Bit domain

* Nested class description

* Type name in class

Class overview

Class Types Use Keywords Class, Struct, and Union. Simply put, use these three keyword definitions called Class Declarations. However, when discussing the language ingredient, the class defined by different keywords is different.

grammar

Class name:

Identifier

A class of variables and functions called a class of classes. Some members are also available when defining a class (although all optional):

* Data members of the class define the properties and status of an object of a class type.

* One or more constructor used to initialize the type of class type. The constructor is described in the "Constructor" section in Chapter 11 "Special Member Function".

* One or more destructor, mainly complete some clearance, such as recycling dynamic allocated memory or shut down files. The destructor is detailed in the "Destructor" section of Chapter 11 "Special Member Function".

* One or more members functions are used to define the behavior of the object.

Define class type

Class Types Definition Use Class-Specifiers. Description of the class type uses a complex type indicator. Introduction to the "Type Description" in Chapter 6, "Description".

grammar

Class specifier:

Type head {member table OPT}

Type head:

Class Keyword Imodel OPT Identifier OPT

Base class Description OPT Class Keyword Imodel OPT

Class Name OPT Base Category OPT Class

Keywords:

Class

Struct

Unionimodel:

__Declspec

When the compiler processes the class name (before processing the type), the class name is immediately as an identifier, so the class name can be used to explain the class member. This allows the user to explain the self-referenced data structure. as follows:

Class Tree

{

PUBLIC:

Void * Data;

Tree * Left;

Tree * Right;

}

Structure, class and joint

The three types of types are structures, classes, and combiners, respectively. Their description is to use Struct, Class and UNION keywords (see keyword syntax). Table 8.1 shows the difference between three types.

Table 8.1 Structure, Class and Joint Access Control and Constraint

The structural class keywords Struct class keyword is the class keyword is Union default access control is public default access control is the private default access control is a public unused constraint. There is only one time. member

Named type

The class can be unkamed. That is, you can explain a class without an identifier. This is useful when you replace a class name with a TypeDef name. as follows:

Typedef struct

{

Unsigned x;

Unsigned y;

Point;

Note: Unspecific use of unnamed use in the above example is useful to keep compatibility with C code. In a lot of C code, Typedef is very common with the unknown structure. When you want to reference a class of members and show that this member is not included in a separate class, the unknown class is also very useful, as shown below:

Struct ptvalue

{

Point ptloc;

union

{

IntiValue;

Long Lvalue;

}

}

PTValue PTV;

In the above code, iValue can be accessed with an object member selector (.). as follows:

INT i = ptv.ivalue;

The unknown class should obey some specific restrictions (see the "Joint" section later behind this chapter for details on unnamed Union). An unknown class:

* No constructor or destructive function

* Cannot be delivered to the function as a parameter (unless "..." avoids type check)

* You cannot use the return value of the function

Class definition point

A class definition is after its class specifier. Member functions do not have to be defined immediately because of the detailed definition of classes.

Study the following example:

Class Point // Point class

{// Detailed definition

PUBLIC:

Point ()

{cx = cy = 0;} // Define constructor

Point (int X, int y)

{CX = X, CY = Y;} // Define constructor

Unsigned & x; / / Define Accessor

Unsigned & y (unsigned); // Define Accessor

Private:

Unsigned CX, CY;

}

Although the two accessor functions (X and Y) have not been defined, the class Point has been detailed (the accessor function is mainly used to provide security access to the data).

Class type object

An object is a type of storage area in the execution environment; it not only retains status information, but also defines behavior. Class Type objects are defined by class name. Expected the following code segment:

Class Account // Class name is Account

{

PUBLIC:

Account (); // default constructor

Account (double); // constructed from Double type

Double & Deposit (double);

Double & Withdraw (double, int);

...

}

Account checkingAccount; // Define class type object

The code of the surface illustrates a class (new type) called Account, then use this new type to define an object called CheckingAccount.

C provides some operations for type objects:

* Assignment. An object can assign a value to another. The default behavior of this operation is a copy of Memberwise. Users can provide a custom assignment to replace the default behavior.

* Initialization with the copy constructor Next is an example of an initialization of the user-defined copy constructor:

* Clearly initialize an object:

Point mypoint = Thatpoint:

Try MyPoint as a Point type object and initialize it to ThatPoint.

* Initialization caused by transmitting parameters. Objects can be passed to functions in pilot values ​​or reference. If they are passed to the function in a pass value, the copy of each object will pass to the function. The default approach to create this copy is a copy of a member mode (MEMBERWISE). Of course, you can also use a custom copy constructor instead of the default copy constructor (a constructor, which has unique parameters for the category of the class).

* Because of the initialization function returns a value, the object has a function returned from the function in a pilot value or a reference. The default method of returning objects in a pilot value is also a copy of a member mode; of course, it can also be replaced by a custom copy constructor. The object returned by the reference mode (with pointer or reference type) is not possible to use an automatic or partial object for the call function. If this is, the object guided by the return value is exceeded before it can be used.

Chapter 12, "Overload" section in "Overload", explains how to define these operators based on a class-based mode.

Empty class

You can explain an empty class, but this type of object has a non-zero value. The following example shows this:

#include (iostream.h)

Class Nomembers

{

}

Void main () {Nomembers n; // Nomembers type object

Cout << "The size of an Object of Empty Class IS:"

<< SizeOf n << endl;

}

The output of the above program is:

The size of an Object of Empty Class IS: 1.

The memory allocated for this object is non-zero. Thus, different objects have different addresses. Due to different addresses, it is possible to identify different objects by comparing the object pointers. Similarly, each member array must have a different address in each member array.

Microsoft Special Office

An empty group occupies zero bytes in its derived class.

Microsoft End

Class name

Inclass descriptions in programs introduce new types (called class names), which describes the same as class definitions in a given conversion unit. In each conversion unit, only a definition of this type can only be there for a given class type. With these new types, users can define objects. The compiler can also be discovered by type checking of the incompatible type of these objects. Here is an example of type check:

Class Point

{

PUBLIC:

UNSIGNED X, Y;

}

Class Rect

{

PUBLIC:

Unsigned X1, Y1, X2, Y2;

}

// With a function prototype with two parameters, one is the Point type, the other is a Rect type reference INT PTIECT (Point, Rect &);

...

Point Pt; Rect

RECT;

RECT = Pt; // Error, type does not match

Pt = Rect; / / error, type does not match

// Error, PtinRect's parameters

COUT << "Point IS" << PtinRect (Rect, Pt)? ":" not "

<< "in Rectangle" << ENDL;

As shown in the above example, the same type detection constraint is followed by the operations (such as assignment and parameter pass) on a class type object and the internal type object.

Since the compiler can distinguish between different class types, the function can be overloaded based on class type parameters and built-in parameters. For more information on overload functions, see Chapter 7, "Substance" in Chapter 12, and "overload" in Chapter 12.

Description and access to class name

The class name can be explained in the global range or in the class range. If the class name is explained in the class range, they actually refer to "Nested Class."

Microsoft Special Office

There is no function definition in the local class description of Microsoft C .

Microsoft End

New class names introduced in the range of classes are hidden in the same name element in the same closed block. To reference the name hidden by the above description, you can only pass the full type, the following example is an example of a hidden name with a full type indicator:

Struct A // Definition a

{

Int a;

}

void main ()

{

Char a = 'a'; // Reconfers the name A as an object

Struct a a a.

...

}

Because the structure indicated by the name A is hidden by the CHAR object indicated by A, it must be used to define a class key Struct when defining the object AObject of type A.

You can of course use a class keyword to explain a class without providing the definition of this class. This unselected class description is only a class name that is introduced for advance references. This technology is useful in the design of other classes to reference other classes in the design, of course, this technology is also useful when the class name must appear in the header file, and this technology is also useful when it is defined. E.g:

//Rect.h

Class Point; // Class Point Uncertainword

Class Line

{

PUBLIC:

INT Draw (Point & PTFROM, POINT * PTTO);

...

}

In the example above, the POINT class name must be provided, but it is not necessary to introduce the definition of the name.

Typedef statement and class

Use the TypeDef statement to name a class type to turn a TypeDef name into a class name. See "Type Indicators" in Chapter 6, "Description" in Chapter 6.

Class member

Category can have the following types of members:

* Member function

* Data member

* Class (including classes, structures, and union), see "Nested Category and Union"

* Enumeration

* Bit domain

* Friends

* type name

Note: You are included in a class description, which includes in a pre-list, however they are not real class members because they are not in the range of classes.

grammar

Member: Member Description Members OPT

Access indicator: member table OPT

Member description:

DECL indicates the OPT member description.

Function Defining OPT;

Limited name;

Member Description:

Member specifier

Member descriptions, members set

Member specifier;

Description Pure indicator OPT

Identifier OPT: constant expression

Pure indicator:

= 0 The purpose of the members:

* Describe the full set of members of the given class

* Note Access (public, private or protected) associated with individual classes (public, private or protected) In the description of the member table, one member can only explain once. Members' again explain the error message. Because a member table is a complete set of members, you can't add members to give a given class in the subsequent class description.

The member specifier cannot contain an initializer, and the initializer will generate an error message as follows:

Class Cantinit

{

PUBLIC:

Long L = 7; // Error: Attempt to initialize a member

Static inti = 9; // Error: must be defined outside class instructions and initialization

}

Since the objects for each given class are created separately to create a static member instance. The correct initialization method is to use the data of the constructor to initialize the member's data (constructor in Chapter 11 "Special Member Function" section). For all objects of a given class type, there is only one shared static data member copy, and the static data member must define in the file range to initialize (see "Static Data Members" behind this chapter on the details of the static data member). The following example shows how to perform these initialization:

Class Caninit

{

PUBLIC:

CANINIT () {l = 7;} // When the new caninit object is created, L

Long L;

Static Int i:

Static Int J;

}

INT caninit :: i = 15; // i defines and initials to 15 in file scope

// Initialization is set in the range of Caninit

INT caninit :: j = i; // The right side of the initializer is in the range of objects to be initialized

Note: Class name caninit must be derived from i to illustrate that i is defined as a member of Caninit.

Class member instructions grammar

Member data cannot be explained as Auto, Extern and Register storage types. However, they can be illustrated as the Static storage type.

The DECL indicator can be omitted in the description of the member function (see the "Indicator" section in Chapter 6, "Description" section in Chapter 6, and the member functions behind this chapter, and "Description" in this chapter "Function" section). Therefore, the following code is legally illustrated by a function of returning an integer:

Class NodeClspec

{

PUBLIC;

Nospecifiers ();

}

When you explain a friend class in a member table, you can omit the member's description. For more information on Friends, see Chapter 6, "Friends Indicators" in Chapter 10, and "Friends" section in Chapter 10 "Members Access Control". Even when a class name has not been defined, it can also be explained as a friend, and is the name of the name.

However, in such a member of this class, a full type indicator syntax must be used. See the following example:

Class Hasfriends

{

PUBLIC:

Friend class notdeclaredyet;

}

In the example above, there is no member description of the class instructions. Because the instructions for NOTDECLAREDYet have not been processed, the usage form of the full type indicator is used: ClassNotDeclaredyet. One of the already explained types can be used in the description of the friend member instructions:

Class alreadyDeclared

{

...

}

Class Hasfriends

{

PUBLIC;

Friend alreadydeclared;

}

Pure indicator (see Examples below) indicates that the virtual function of this will not be implemented. Therefore, the pure indicator can only be used on the virtual function, and the following code is examined:

Class strbase // strings base class

{

PUBLIC:

Virtual int islessthan (strbase &) = 0;

Virtual ISEqualto (strbase &) = 0;

Virtual strbase & copyof (strbase &) = 0;

...

}

A abstract class is illustrated in the code, that is, this class is designed as a base class to derive more unique classes. By using a pure indicator to illustrate one or more virtual functions as a pure virtual function, this base class can force a special protocol or mechanism.

Classes from StrBase must be implemented for these pure virtual functions. Otherwise they will also be considered an abstract base class.

Abstract base classes cannot be used to illustrate objects. For example, before a class inherited from the StrBase class, you must provide a function islessthan, ISEQUALTO, and CopyOF implementation (more information on abstract base classes) "Abstract classes" in Chapter 9 " . Meeting in member table

Microsoft Special Office

If a program is not compiled with an ANSI compatibility option (/ za), the growth array can be explained in the class member table as the last data member. Because this is the expansion of Microsoft, so use this way to use the growing number group to reduce your transplantability. Note An array of growth, omitted the first dimension, such as:

Class Symbol

{

PUBLIC:

Int symboltype;

CHAR SYMBOLTEXT [];

}

Microsoft End

limit

If a class contains a growing array, it cannot be used as a base class of other classes, and a class containing the bearing length array cannot be casually explained as a member of other classes, and can only explain the last member of other classes. A class containing a growing array does not contain a direct or indirect virtual base class. When the SIZEOF operator is used in a class containing a growing array, the storage sum of all members other than the extended length array is returned. For the implementation of classes containing the growth array, an alternative approach should be provided to obtain the correct class.

It is not possible to explain the object containing the constituent components as a member of a group, and a mathematical calculation is made for a pointer to such objects.

Class member data storage

Non-static member data stores as follows: All items between the access specifiers are stored in a direction increasing to the memory address. The order of storage of members of the access specifier is not guaranteed.

Microsoft Special Office

Depending on the / zp compilation option or contains the PRAGMA pseudo directive, the intervention can be introduced to make the member data or double word boundary alignment. In Microsoft C , class members are stored in the direction of adding address, although this is not requested. Basic assumptions about this order can cause non-portable code.

Microsoft End

Members naming restrictions

The function of the same name is the same name in the class description is a constructor. When an object of this class is created, the constructor is implicitly called (see Chapter 11 "Constructor" section in Chapter 11, "Things Functions" in Chapter 11.

In the scope of the description, various names cannot be classified: data members (static or non-static), closed enumerations, unknown joint members and nested classes.

Member function

Classs can include data and functions, which are called member functions. Any non-static function illustrated in the class description is considered as a member function and calls with the member selectors (. And ->). When the member function of this class is called in other member functions, the object and member selectors can be omitted. E.g:

Class Point

{

PUBLIC:

Short x () {return _x;}

Short y () {return _y;

Void show () {cout << x ()> <"<" <"> <" / n ";}

Private:

Short _x, _y;

}

void main ()

{

Point pt;

Pt.show ();

}

Note: Other member functions X and Y are called in the member function show, and the member selectors are not used. The implicit meaning of these calls is this-> x () and this-> y (). However, call the member function SHOW in the main function main must use the object PT and member selectors (.).

Calls of static member functions illustrated in the class can use member selectors or use full-qualified function names (including class names).

Note: The function described with Friend keyword does not consider a member of the class. This function is only description as a friend (although this function can be a member of the class).

A friend instructions control the access of the non-member function to class data.

The following example shows how to explain the member function:

Class Point

{

PUBLIC:

UNSIGNED getx ();

UNSIGNED getY ();

Unsigned setx (unsigned x);

Unsigned set (unsigned y);

Private:

UNSIGNED PTX, Pty;

}

In the above description, four functions are illustrated: getx, gety, setx, and sety. The following example shows how to call these functions in the program: void main ()

{

/ / Describe a Point type object

Point ptorigin;

// Call the member function with a member selector (.)

Ptorigin.setx (0);

Ptorigin.sety (0);

/ / Describe a pointer to the Point type object

Point * pptcurrent = new point;

// call member functions with member selectors (->)

PPTCurrent-> setx (ptorigin.getx () 10);

PPTCurrent-> Sety (ptorigin.gety () 10);

}

In the above code, the call of the object PTORIGIN member function is called with the member selector (.). The call of the member function of the object pointing by PPTCurrent is used as a member selector (->).

Member function overview

The member function can be static or non-static. The behavior of static member functions is different from the behavior of other member functions because the static member function does not have an implicit THIS parameter. Non-static member functions have a THIS pointer. Regardless of whether static member functions or non-static member function members can be defined outside of class instructions.

If it is defined within the class description, it is considered embedded function, nor is therefore necessary to define the function name by class name. Although the function defined in the class description is already treated as an embedded function, you can still use the keyword inline to document the code.

Here is an example of defining a function in a class description:

Class Account

{

PUBLIC:

// Description of the function deposit in the class account statement

Double Deposit (double howmuch)

{

Balance = howmuch;

Return balance;

}

Private:

Double balance;

}

When a member function is defined outside the class description, it is only clearly described as inline, which is considered to be embedded member functions. And the function name must be defined by the function name when defined.

The following example except that the function deposit is defined outside the class description, it is equivalent to the previous confinement account.

Class Account

{

PUBLIC:

// Describe the member function deposit, but does not define it.

Double Deposit (double howmuch);

Private:

Double balance;

}

Inline Double Account :: Deposit (double howmuch)

{

Balance = howmuch;

Return balance;

}

Note: Although the member function can be defined separately in the class description, it can be individually defined outside the class instructions, but it cannot add member functions to it when the class defines.

The class containing the member function can have multiple instructions, but the member function itself is only one definition in the program. Multiple definitions will lead to an error message when link. If a class contains the definition of the wedge function, the definition of this function also needs to meet the "unique definition" principle.

Non-static member functions

Non-static member functions have an implicit parameter, this, which is a pointer to the object that calls this function.

The THIS pointer is Type * const. These functions are considered to have a range of classes that can be directly used in the same class data and member functions. In the previous example, the expression Balance = HowMh plus the value of howMUCH in the class member Balance. Expected the following statement:

Account checking;

Checking deposit (57.00);

In the example above, an object of an Account type is illustrated and the member function deposit is called $ 57.00. In the function account :: Deposit, Balance as Checking.Balance (the object of the object's Balance member).

Non-static member functions tend to operate on their own class type objects. Calling this member function can cause uncertain behavior by converting this member function to the other different types of objects.

THIS pointer

All non-static member functions can use this keyword, this is a constant pointer (cannot be modified). It points to the object is the caller of the member function. Member data can be determined by the value of the expression this-> member name (although this technology is rarely used). In a member function, use the member name in the expression that hides the use of the THIS-> member name to select the correct function and data member. Note: Because the THIS pointer is unmodified, the THIS is not allowed. The THIS pointer is allowed in the implementation of the early C .

Occasionally use the THIS pointer. For example, when manipulating the self-citing data structure, the address of the current object is obtained in this case.

That pointer

The THIS pointer can be modified in the function description through the const and volatile keywords. To illustrate a function with these keyword properties, use CV-modifier syntax.

grammar:

CV-modifier table:

CV-modifier CV-modifier table

OPTCV-modifier:

Const

Volatile

Consider the following example:

Class Point

{

Unsigned x () const;

}

A member function x is illustrated in the example above, where the THIS pointer is treated as a constant pointer to the constant object. It can be mixed using the CV-modifier table option, but they are usually modified the object referred to by the THIS pointer, not the THIS pointer itself. Therefore, the function is explained in the following description, its THIS pointer is a constant pointer to the constant object:

Class Point

{

UNSIGNED X () __ far const;

}

The following grammar describes the type of the THIS pointer, where the CV-modifier table can be const or volatile, class name is the name of the class:

CV-modifier Table OPT class * constim

Table 8.2 explains more roles related to these modifications.

Table 8.2

The modifier meaning constST cannot change the member data, and you cannot call a very variant member function Volatilee member data to be transferred from the memory at a time; and turn off the optimization

Pass a constant object to a very quite member function generate an error. Similarly, pass a Volatile object to a non-Volatile type function also generates an error.

The member function is described as a const type, and the member data cannot be changed. In this function, the THIS pointer is a pointer to a constant.

Note: The constructor and the destructor cannot be explained as const or volatile. However, they can be called by Const or Volatile object.

Static member function

Static member functions are considered to have a range of classes. Compared to non-static members, these functions have no implied THIS parameters; thus they can only use static data members, enumerations or nested types. State member functions can not have to have a corresponding class type object. Consider the following code:

Class WindowManager

{

PUBLIC:

Static int countof (); // Return to the number of open window

Void minimize (); // Minimize current windows

WindowManager Sideeffects (); // Boundary Effect (side effect) function

...

Private:

Static int wmwindowcount;

}

INT WINDOWMANAGER :: WMWINDOWCOUNT = 0;

...

// Minimize (display icon) all windows

For (int i = 0; i

RGWMWIN [I] .minimize ();

In the code above, class WindowManager contains a static member function countof. This function returns the number of opens the window, but does not have to contact a given WindowManager class object. This concept is reflected in the cycle. COUNTOF in the cycle is used to control the expression. Because Countof is a static member function, this function can be called without reference objects. Static member functions have external connections. These functions have no THIS pointer (discusses in the next chapter). As a result, these functions must follow some of the following constraints:

* You cannot use member selectors (. Or ->) to access nonstatic members.

* You cannot explain the virtual function.

* The same name cannot be the same name with a non-static member function with the same parameter type.

Note: The member selector (. Or ->) of a static member function is selected, and the left is unrecognizable. This may be important when there is a function of side effects with this function. For example: Expression Sideeffects (). Countof () does not call the Sideeffects function. Static data member

Category can include static member data or member functions. When a data is static, all objects of this class maintain only one copy of the member (related situations see the "Static Member Function" of the previous section).

Static data members are not part of a given class object; they are separate objects. As a result, the instructions for static data members cannot be considered as definitions. The instructions of the data are in the class range, but they define

It is implemented in the file range. These static members have external connections. The following example shows this:

Class bufferedoutput

{

PUBLIC:

/ / Return the byte size written by this class object

Short byteswritten () {return bytecount;

// Reset Counter

Static void resetcount () {bytecount = 0;}

// Description of static members

Static Long Bytecount;

}

/ / Definition in the file range bytecount

Long bufferedoutput :: bytecount;

In the previous code, members Bytecount is illustrated in class bufferoutput, but it must be defined outside of class instructions.

You don't have to reference a certain type of object to reference static data members. The byte size written in the bufferedoutput object can be obtained as follows:

Long nbytes = bufferedoutput :: Bytecount;

Static members will not end due to the end of the type of object. Static members can of course access them with a member selector (. Or ->). E.g:

BUFFEREDOUTPUT CONSOLE;

Long nbytes = console.bytecount;

In the above example, reference to the object console is not available. The returned value is a static object bytecount.

Static data members are also subject to access rules for class members, so privately stored static data members only allow class member functions and friend access. These rules are described in Chapter 10, "Members Access Control". The exception is that static data members must be defined in the file range and ignore their storage constraints. If the data member should be explicitly initialized, the initializer must be provided with the definition.

The type of static member is not limited by its class name. So: bufferedoutput :: Bytecount is a long type.

Join

A combined type can only include a data element at a point in time (although the data element can be an array or class type). A joint member represents the type of data that the joint can contain. A joint type of object requires enough space to accommodate the largest members in the member table. Consider the following example:

#include

#include

#include

Union NumericType // Description A combination that can accommodate the following data

{

INT IVALUE; // Integer value

Long Lvalue; // Long integer value

Double Dvalue; // floating point value

}

Void main (int Argc, char * argv [])

{

NumericType * VALUES = New NumericType [ARGC-1];

For (int i = 1; i

{

IF (Strchr (Argv [I], '.')! = 0)

/ / Floating point assignment with DVALUE members

VALUES [I] .dvalue = atof (argv [i]);

Else

/ / If it is greater than the maximum integer, save it to the Lvalue member.

IF (ATOL (Argv [I])> INT_MAX)

VALUES [I] .lvalue = atol (argv [i]);

Else

/ / Otherwise, save it to the iValue member

VALUES [I] .Ivalue = atoi (argv [i]);

}

The location diagram of NUMERICTYPE in the memory is shown in Figure 8.1.

Joint member functions

As described in the member function, in addition to the member data, the combination can also have a member function, although there can be special member functions such as constructor and destructive functions, but the combination does not have virtual functions (more information about more information) See "Constructor" and "Destructor" in Chapter 11 "Special Member Functions").

As a federated combination of class type

There is no base class; therefore, they cannot inherit attributes from other joints, structures, and classes. The combination cannot be used as a base class further inherited.

Inheritance will be discussed in detail in Chapter 9, "Delivery".

Union member data

In addition to the following, the combination can contain most of the data types in the member table:

* Type type with constructor or destructor

* Class type with custom assignment operators

* Static data member

Unknown union

The unnamed combination is a union of the name or instructions when explaining.

grammar

Union {member table};

This joint explanation is not illustrated, but an object. The name illustrated in the unkname Union cannot be conflicted with other names in the same range. The name illustrated in the unkname is directly used, just like not the member variable. The following example shows this.

#include

Struct DataForm

{

ENUM DATATYPE {Chardata = 1, INTDATA, STRINGDATA};

DataType Type;

// Description An unintended union

union

{

Char chcharmem;

Char * szstrmem;

INT IintMem;

}

Void print ();

}

Void DataForm :: Print ()

{

// Based on Type's data type printing the right data type

Switch (Type)

{

Case Chardata:

Cout << chcharmem;

Break;

Case INTDATA:

Cout << SzstrMem;

Break;

Case stringdata:

Cout << intmem;

}

}

In the function dataform :: print, three members (CHCHARMEM, SZSTRMEM, and IINTMEM) are just like they are the same as members of the member (without a joint description). However, three union members are shared with the same memory.

In addition to some of the above constraints, the joint member data is limited by the following constraints:

* If in the file range, it must be static.

* They can only contain public members; the private and protected members will generate errors in the unknap.

* They can't have member functions.

Note: Only simply omitted the syntax section of the class name of the syntax does not make a unintegrated unnamed, and a joint limit is not nameless, then the object must not be described.

Domain

Classs and structures can have less than one integer in the storage space. These members are illustrated as a bit domain. The syntax specifications of the bitmap member statement are as follows:

grammar

Description OPT: constant expression

The specifier is the name used to store members in the program. It must be an integer (including enumeration type). A constant expression illustrates the number of people occupied in the structure. The unknapped domain is also a bit domain member without an identifier, which can be used as a fill.

Note: An unnamed zero width bit domain will force the next bit field to the next type boundary. Here the type refers to the type of member.

The following example illustrates a structure containing a bit field:

Struct Date

{

Unsigned nweekday: 3; //0..7 (3)

Unsigned nmonthday: 6; //0..31 (6)

Unsigned nmonth: 5; //0..12 (5)

Unsigned nyear: 8; //0..100 (8)

}

A memory layout of a DATE type object is shown in Figure 8.2.

Note: NYEAR is a word boundary that is 8-bit long and exceeds the designed int type. So Nyear continues on a new unsigned int. There is no need to plug all bit fields into a type-based type object. The new storage unit can be allocated according to the size of the bit field required in the description.

Microsoft Special Office

The order of the data as a bit domain description is from low to high. Microsoft End

If a zero length bit field is included in the structural description, as shown in the following example:

Struct Date

{

Unsigned nweekday: 3; //0..7 (3)

Unsigned nmonthday: 6; //0..31 (6)

Unsigned: 0; // Forced alignment to the next boundary

Unsigned nmonth: 5; //0..12 (5)

Unsigned nyear: 8; //0..100 (8)

}

The memory distribution is shown in Figure 8.3.

The type based on the bit domain must be integer. See Chapter 2 "Basic Concept" in the basic type.

Use a bit domain limit

The following is a detailed error operation of the counterpart field:

* Take a bit domain address

* Initialization

Nested description

Category can be described in other classes. This type is called "nested class". Nested classes are considered to be in the range of peripheral closure, and can only be used effectively in this effect. To reference a nested class, you must use a fully qualified name.

The following example shows how to explain the nested class.

Class bufferedio

{

PUBLIC:

Enum orerror {none, access, general};

// Description Nested BufferedInput

Class bufferedinput

{

PUBLIC:

Int read ();

INT good () {return_inputerror == none;}

Private:

Orerror _inputerror;

}

// Description Nested Bufferedoutput

Class buufferedoutput

{

// member table

}

}

Bufferedio :: Bufferediuput and Bufferedio :: BufferedOutput is illustrated in bufferedio. These types of names are invisible outside the class bufferedio range. But a bufferedio type object does not contain any bufferediuput and bufferedoutput objects. Nested classes can directly use names, static member names, type names, and enumeration names from the periphery.

In order to use other class members, the name of the pointer, reference, or object must be used.

In the example of bufferedio above, enumeration IOerror can be accessed directly by the members of the nested bufferedio :: bufferedIO :: BufferedInput and Bufferedio :: bufferedoutput. As shown in the functionality.

Note: Nested classes only illustrate the type only in the class range. It does not cause objects that create nested classes. The above example only illustrates two nested classes but does not indicate any objects of any of these classes.

Access rights and nested classes

Nested classes in other classes do not give a member of the nested class to special privileges. Similarly, there is no special access to members of the member functions included in the class.

Member function in nested classes

The member function described in the nested class can be defined in the file range, the previous example can be written as:

Class bufferedio

{

PUBLIC:

Enum orerror {none, access, general};

Class bufferedinpu

{

PUBLIC:

INT read (); // Description but does not define member functions read and good

Int good ();

Private:

Orerror _inputerror;

}

Class bufferedoutput

{

// member table

}

}

/ / Define member functions Read and Good in the file range

Int bufferedio :: bufferedInput :: read ()

{

...

}

Int bufferedio :: bufferedInput :: good ()

{

Return _inputer == none;

}

In the above example, use the Limited Type Name syntax to illustrate the member function name, indicating:

Bufferedio :: bufferedinput :: read ()

Means the function read is a member function of the BufferedInput class in the range of class bufferedio. Because this statement uses a defined type name syntax, the following form is possible: typedef buffremedio :: bufferedinput bio_Input

INT BIO_INPUT :: read ()

The above instructions are equivalent to the previous description, but it replaces the class name with a TypeDef name.

Friends functions and nested classes

The friend function described in the nested class is considered to be in the range of nested classes, not in the range of classes. Therefore, for those members and member functions included in the class, these friend functions have not obtained how much special access. If you want to use a name in the nested class in the friend function defined in the file, you must use the qualified type name as below:

Extern char * rgszmessage [];

Class bufferedio

{

PUBLIC:

... Class BufferedInput

{

PUBLIC:

Friend int getExtendedErroStatus ();

...

Static char * message;

INT IMSGNO;

}

}

CHAR * BUFFEREDIO :: BufferedInput :: Message

Int getExtendedErrorstaus ()

{

...

Strcpy (Bufferedio :: BufferedInput :: Message,

RgszMessage [IMSGNO]);

Return IMSGNO;

}

The function getExtendedErrorStatus is instructions in this function (which is defined in the file range) as a member of the program (it defines the file range), and a message is copied from the static array to the class member. Note that a better implementation of getExtendedErrorStatus is description:

Int getExtendedErrorStatus (char * message)

With the previous interface, several different classes can use this function of this function, just pass the address of the error message to be copied to the function.

Type name in class

The type name defined in the class range should be considered to be limited to their classes. They cannot be used outside the scope of the class.

The following example shows this concept:

Class Tree

{

PUBLIC:

Typedef tree * ptree;

PTree Left;

PTREE RIGHT;

Void * vdata;

}

PTree Ptree; // Error: Not in the range of classes

转载请注明原文地址:https://www.9cbs.com/read-46724.html

New Post(0)