Chapter 13 explains

xiaoxiao2021-03-06  15

Chapter 13 explains

A "specifier" is part of the description to name an object, type, or function. The specifier is a name that appears in one or more comma, each name can have a related initializer.

grammar

Description Table:

Initial explanatory

Description Table, initial explanatory

Initial explanatory:

Indicator initializer OPT

This chapter includes the following topics:

* Description Overview

* type name

* Abstract specifier

* Function definition

* Initializer

Description Overview

The specifier is a description of the specified name. The specifier can also modify the basic type information such that the name becomes a function or object or function (in Chapter 6, "Description", is transmitted such as type and storage class properties. In this chapter, Appendix B "Microsoft Special Modification The modifier discussed in the accord uses a modified specifier).

Figure 7.1 shows a complete description of two names SZBUF and STRCPY, and the components of the description are proposed.

Microsoft Special Office

Most Microsoft expansion keys can be used as a modifier that forms a derived type; they are not an indicator or a setup (see Appendix B "Microsoft Special Modifier").

Microsoft End

grammar

Reference:

DNAME

PTR operator

Description (Paral Description Table) CV modified meter

Description [constant expression OPT]

(Indicator)

PTR operator:

* CV Limit Table OPT

& CV Limit Table OPT

Complete Class Name :: * CV Limit Table

OPTCV Limit Table:

CV Limit CV Limit Table

OPTCV qualifier:

Const

Volatile

CV modified meter:

CV Limit CV Modification Table OPT

PModel CV Modification Table Opt

DNAME:

name

Class name

~ Class name

TypedEf name

Limited type name

The specifier appears behind the description syntax, which is discussed in Chapter 6, "Description" in Chapter 6. An instructions can include nothing one specifier, but each specifier illustrates only one name. The following describes how the sample shows how the indicator and the specifier are combined to form a complete description:

Const char * PCH, CH;

In the previous description, keyword const and char have form a indicator table. Two specifiers * PCH and CH are listed.

Then a simplified syntax is as follows, where const char is type, * pch and ch is the specifier: Type Declarator1 [, Declarator2 [..., DECLARATORN]];

When the element is coupled to a description table does not produce the desired result, you can use parentheses to make it clear. But a better technology is to use typedef or parentheses combination and TypeDef keywords. Consider an array of pointers in a function. Each function must follow the same protocol, so the parameters and return values ​​are known:

// Function Return Type Int, with a char * type parameter

Typedef int (* pifn) (char *);

/ / Describe an array of 7 function pointers, returns int, with a char * type parameter

PIFN PIFNDISPATCHARRAY [7];

The equivalence instructions can be written in TypeDef, but it is too complicated, but makes the wrong potential beyond its benefits:

int (* pifndispatcharray [7] (char *);

type name

Type names are used in some specifiers as follows:

* In explicit conversion

* As a parameter of the Sizeof operator

* Paramends as a New operator

* In the function prototype

* In the TypeDef statement

A type name constitutes a type indicator, as discussed in Chapter 6, "Description", and the next section "Abstract Description".

In the following example, the parameters of the function STRCPY are provided by using their type names. In the Source Parameter, const char is an indicator, * is an abstract specifier:

Static Char * SZBUF, * STRCPY (Char * DEST, Const Char * Source);

grammar

type name:

Type Indicator Watch Abstract Indicator OPT

Type indicator:

Type Indicator Type Indicator Table OPT

Abstract specifier:

PTR operator abstract specifier OPT

Abstract Indicator OPT (Patroduck Description) CV Limit Table OPT

Abstract specifier OPT [constant expression OPT]

(Abstract specifier)

Abstract specifier

A abstract specifier is a setup, which omitted the identifier (related information "Type Name").

This section discusses the following abstract specifiers:

* Pointer

* Reference

* Member pointer

* Array L function

* Default parameters

A abstract specifier is an explanatory that does not indicate a name, that is, the identifier is omitted. For example: char *

Description Type "Pointer to CHAR Type". This abstract specifier can be used in a function prototype as shown below:

CHAR * STRCMP (Char *, Char *);

In this prototype (description), the parameter of the function is specified as an abstract set. The following is a more complex abstract specifier, indicating a pointer to a function with two parameters, and is a CHAR * type function, return type char *:

Char * (*) (char *, char *)

Since the abstract specifier completely illustrates a type, the expression in which the following form is legally: // Gets the size of the array of 10 pointers of a char type.

SIZE_T nsize = sizeof (char * [10]);

// Assign a pointer to a function pointing to the return value and without a parameter

TYPEDEF VOID (PVFN *) ();

PVFN * PVFN = New PVFN;

// Pointer array of // functions that returns a type of WINSTATUS and a WinHandle type

Typedef WinStatus (WinHandle);

PWSWHFN PWSWHFNARRAY [] = New PWSWHFN [10];

Fuzziness solution

To perform explicit conversion from a type to another, you must use forced conversion to point out the desired type name. Some types of modeling conversion leads to syntax ambiguity, and the following function forms for mandatory conversion is blurred:

Char * aname (String (s));

Unclear it is a function description, or an object that enforces the function form as an initializer description: it may illustrate a return type char *, and bring a string type parameter function, or may indicate the object aname, and use S The value of the shape is converted to the type String to initialize it.

If a description can be considered a valid function description, it is treated like this. Only when it is impossible to be a function description - ie, if it is a syntax error - is a statement to detect it is a function form type modeling conversion. Therefore, the compiler uses the statement as a function of a function and ignores the parentheses around the identifier S. On the other hand, statement:

Char * aname ((string) s);

with

Char * aname = String (s);

It is an object's clear description, and a user-defined conversion from a String type to a CHAR * type is called to perform an initialization of aname.

Pointer

The pointer is explained using the specification syntax:

* CV Limit Table Opt DNAME

A pointer has an address of an object. Then a complete explanation is:

Description Indicator * CV Limit Chart Opt DNAME;

A simple example of this description is:

CHAR * PCH;

The description of the above specifies the PCH to point to a CHAR type.

Const and Volatile pointers

Const and Volatile Keyword changed pointers are treated. The const keyword specifies that the pointer cannot be modified after initialization, the pointer is protected from then that it is protected and cannot be modified.

The Volatile Keyword Specifies that the value related to the following name can be modified by those that are not in the user application, so the Volatile keyword is connected to the shared memory that can be accessed by multiple procedures or communication with interrupt service routines. The object is very useful in the global data area.

When a name is illustrated as Volatile, the compiler reloads its value from the memory each time you are accessed, which greatly reduces possible optimization. However, when an object's status may be unexpectedly changed, it is the only way to ensure that the program can predict.

To illustrate objects pointed to by the Const or Volatile pointer, use this form:

Const char * cpch;

Volatile char * vpch;

To illustrate the pointer value, that is, the actual address stored in the pointer is const or volatile, using this form:

Char * const pchc;

Char * Volatile PCHV;

The C language does not allow the modification of the pointer or object that is declared Const, which will remove the information used in the object or pointer, so conflict with the intentions of the source, consider the following instructions: const char cch = 'a "

Charch = 'b';

The description of the two objects preceded (CCH is const char type, CH is a CHAR type), then the following instructions / initialization is effective:

Const char * PCH1 = & CCH;

Const char * const pch4 = & cch;

Const char * pch5 = & ch;

CHAR * PCH6 = & ch;

Char * constpch7 = & ch;

CONST Char * const pch8 = & ch;

The following instructions / initialization are erroneous:

Char * PCH2 = & CCH; / / Error

Char * const pch3 = & cch; // errors

The instructions of the PCH2 have passed a constant object that may be modified and therefore not allowed. The description of the PCH3 specifies that the pointer is constant, not an object, which is not allowed in connection with the PCH2 instructions without allowing the same reason.

The following 8 assignments show the assignment of the pointer and the case of changing the pointer value, now, suppose that the initialization from the PCH1 to PCH8 is correct:

* PCH1 = 'a'; // Error: Object Description Constant

PCH1 = & ch; // Viable: The pointer is not illustrated as a constant

* PCH2 = 'a'; // Viable: Normal pointer

PCH2 = & ch; // Viable: Normal pointer

* PCH3 = 'a'; // Viable: Object is not illustrated as constant

PCH3 = & ch; // Error: Pointer description as constant

* PCH4 = 'a'; // error: Object Description as constant

PCH4 = & ch; // Error: Pointer description as constant

The pointer compliance compliance complies with the Volatile or Const and Volatile is the same rules. Pointer to the Const object is often used in the following function description:

Char * STRCPY (Char * sztarget, const char * szsource);

The previous statement illustrates a function strcpy with two types of "CHAR pointer" and returns a pointer to the char type. Since the parameter is passed by the reference, not by value passed, if the szsource is not illustrated as const, the function is free to modify SZTARGET and SZSource. Trying SzSource as constant to ensure that the caller SzSource cannot be called.

Note: Due to the presence of a standard conversion from TypenAme * to Const Typename *, it is legal to pass a type char * to Strcpy. However, it is otherwise, there is no implicit conversion from an object or pointer to remove the const attribute.

The given type of Const pointer can be assigned a pointer to the same type. However, a pointer not constant cannot be assigned to a const pointer, the following code gives the correct and error assignment:

INT * const cpObject = 0;

Int * pobject;

void main ()

{

POBJECT = CPObject; // Viable

CPOBJECT = POBJECT; / / Error

}

Introduce

Quote Use the instructions grammar to explain:

grammar

& CV Limit Table Opt DNAME

A reference has an address of an object, but the syntax behaves like an object. A reference description includes a (optional) specified table, followed by a reference specifier.

grammar

Description Indicator & CV Limit Chart Opt DNAME;

Consider user-defined types of Date: struct date

{

Short dayofweek;

Short month;

SHORT DAY;

Short year;

}

The following statement describes a reference to a Date type object and a reference to that object:

Date Today; / / Description Object

Date & Todayref = Today; / / Description Reference The reference object name Today and the reference TodayRef can be used exactly the same manner in the program:

Today.dayofweek = 3; // Tuesday

TodayRef.month = 7; // july

Reference type function parameters

It is usually more efficient than the transfer function to a large object. This allows the compiler to pass the address of the object when maintaining the syntax used to access the object. Consider using the Date structure below:

// Create a DDDYYYY in the form of a DDDYYYY in the date of the Julian Date

Long Julianfromgorian (Date & gdate)

{

Static int CDAYSINMONTH [] = {

31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31

}

Long jdate;

/ / In the past month, add the number of days

For (int i = 0; i

JDATE = CDAYSINMONMONTH [I];

/ / For the number of days this month

JDATE = gdate.day;

// Check the year

IF (gdate.year% 100! = 0 && gdate.year% 4 == 0)

JDATE ;

//

Jdate * = 10000;

JDATE = gdate.year;

Return JDATE;

}

The front code shows that the consolidation of the conscript by reference is accessed using the member selection operator (.) Instead of the pointer selection operator (->).

Although the pointer to the reference type is followed from the non-pointer type syntax, they retain an important feature of the pointer type: they are modified unless they are explained. Because the intent of the previous code is not modifying the object GDATE, a more appropriate function prototype is:

Long julianfromgorian (const date ";

This prototype guarantees that JulianFromgorian does not change its parameters.

Any function with reference type prototyping can accept an object of the same type at its location, because from TypenAme to Typename & a standard conversion.

Reference type function returns

The function can be explained to return a reference type. There are two reasons for this description:

* The information that is returning is a sufficiently large object, returns a reference than returns a copy efficiency.

* The type of function must be a l value.

Just as the object passes a large number of objects can be more efficient, it can be more effective by returning a large object from a function. The reference return protocol removes the necessity of copy objects to returns the previous temporary place.

The reference return type is also useful when the function must obtain a value of one l value. Most overload operators are such, especially assignment operators. The overloaded operator contained "overloaded operators" in Chapter 12 "Overload", considering the Point example in Chapter 4 "Expression":

Class Point

{

PUBLIC:

/ / Define the Accessor function as a reference type

Unsigned & x ();

UNSIGNED & Y ();

Private:

Unsigned obj_x;

Unsigned obj_y;

}

Unsigned & points :: x ()

{

Return Obj_x;

}

Unisgned & Point :: Y ()

{

Return Obj_y;

}

void main ()

{

Point thepoint;

// use x () and y () as a l value

Thepoint.x () = 7;

= 9;

// Use x () and y () as the R value

COUT << "x =" << thepoint.x () << "/ n"

<< "y =" << thepoint.y () << "/ n"

}

Note Functions X and Y are description to return reference types. These functions can be used for any side of an assignment statement. The description of the reference type must include the initializer, except: * Display Extern description.

* Description of a class member.

* In a class.

* The parameter or function returns the type of function.

Pointer reference

The pointer reference and object reference will be described in terms of the same manner. Note The reference to a pointer produces a modified value that is used as the normal pointer. The following code example illustrates the difference between the pointer to the pointer and a reference to a pointer:

#include

#include

/ / Define a binary tree structure

Struct btree

{

Char * sztext;

BTree * Left;

BTREE * RIGHT;

}

/ / Define a pointer to the root of the tree

Btree * btroot = 0;

INT Add1 (btree ** root, char * sztoAdd);

INT Add2 (btree * & root, char * sztoAdd);

Void Printtree (btroottree);

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

{

IF (Argc <2)

{

CERR << "usage: refptr [1 | 2]" << "/ n";

CERR << "/ n / twhere: / n";

CERR << "/ T1 Uses Double Indirection / N";

CERR << "/ T2 Uses a reference to a point./N";

CERR << "/ n / tinput is from stdin./n";

Return 1;

}

Char * szbuf = new char [132];

/ / Read a text file from the standard input device and construct a binary tree

While (! cin.eof ())

{

Cin.get (SZBUF, 132, '/ N');

cin.get ();

IF (Strlen (SZBUF))

Switch (* argv [1])

{

// Method 1: Use a double indirect reference

CASE '1':

ADD1 (BTROOT, SZBUF);

Break;

// Method 2: Use a pointer reference

Case '2':

ADD2 (BTROOT, SZBUF);

Break;

DEFAULT:

CERR << "illegal value" << * argv [1]

<< "Lsupplied for Add Method./N"

<< "Choose 1 or 2./N";

Return -1;

}

}

// Display the ranking table

PRINTTREE (BTROOT);

Return 0;

}

// PRINTTREE: Show binary tree

Void PrintTree (btroottree (BTree * btroot)

{

// Recursively traverse the left subtree

IF (btroot-> left)

PRINTTREE (BTROOT-> Left);

// Print the current node

COUT << btroot-> sztext << "/ n";

// Recursively traverse the right tree

IF (btroot-> right)

PRINTTREE (BTROOT-> RIGHT);

}

// Add1: Add a node to the binary tree

// use double indirect connection

Int Add1 (btree ** root, char * sztoadd)

{

IF ((* root) == 0)

{

(* Root) = new btree;

(* Root) -> left = 0;

(* Root) -> Right = 0;

(* Root) -> sztext = new char [Strlen (SZTOADD) 1]; STRCPY ((* root) -> sztext, sztoAdd;

Return 1;

}

Else IF ((* root) -> sztext, sztoAdd> 0)

RETURN ADD1 (& (* root); SZTOADD);

ELSE RETURN ADD1 (& (* root) - (Right), SztoAdd;

}

// add2: Add a node to the binary tree // Use the pointer reference Intd2 (btree * & root, char * sztoAdd)

{

IF (root == 0)

{

Root = new btree;

Root-> left = 0;

ROOT-> Right = 0;

Root-> sztext = new char [strlen (sztoAdd) 1];

STRCPY (root-> sztext, sztoAdd);

Return 1;

}

Else IF (strcmp (root-> sztext, sztoAdd)> 0)

Return Add2 (root-> left, sztoAdd);

Else

Return Add2 (root-> right, sztoAdd);

}

In the above program, functions add1 and add2 are equivalent (although they are called in different ways). The difference is that the ADD1 uses a double indirect reference to the ADD2 uses a convenient pointer reference.

Member pointer

The description of the member pointer is the special case of the pointer.

grammar

Indicator

Class Name: * CV Limit Chart Opt DNAME;

Pointer to a class member is different from a normal pointer because it has a member type and the type information of the class. A normal pointer only identifies a single object in the memory memory. A class member pointer identifies the member of any instance of the class. The following example illustrates a class Window and some member data pointers:

Class Window

{

PUBLIC:

WINDOW (); // Default constructor

Window (int x1, int y1, // constructor specified window size

INT x2, int y2);

Bool setcaption (const char * sztitle); // set window title

Const char * getcaption (); // Get window titles

Char * szwincaption; // Window header

/ / Describe a pointer to the data member szwincaption

Char * window :: * pwcaption = & window :: szwincap

In the above example, PWCAPTION is a pointer to any member of the CHAR * type of WINDOW. The type of PWCAPTION is char * window :: *. The following code segment illustrates a pointer to the setcaption and getCaption members.

Const char * (window :: * pfnwgc) () = & window :: getcaption;

Bool (window :: * pfnwsc) (const char *) = & window :: setcaption;

Pointers PFNWGC and PFNWSC points to the Window class GetCaption and SetCAption, respectively. This code is copied directly to the window title by using the member PWCAPTION pointer:

Window WMAINWINDOW;

Window * pwchildwindow = new window;

Char * szuntitled = "uns);

INT Cuntitledlen = Strlen (Szuntitled);

STRCPY (WMAINWINDOW. * PWCAPTION, SZUNTITED);

(WMAINWINDOW. * PWCAPTION) [Cuntitledlen-1] = '1'; // The same //wmainwindow.szwincaption []='1 ';

STRCPY (PWCHildWindow -> * Pwcaption, Szuntitled);

(PWCHILDWINDOW -> * PWCAPTION) [Szuntitledlen-1] = '2'; // is the same below

// pwchildwindow-> szwincaption [] = '2' ;.

* And -> * Operators (member pointer operators) differences:. * Operator via a given object or object

Quote Select members, and -> * Operators Select a member (more information on these operators) "Expression" in Chapter 4 "Expression" in Chapter 4 "Expression" in Chapter 4 ").

The result of the member's pointer operator is the type of member, in this case, CHAR *.

The following code segment uses the member pointer call member function getcaption and setcaption:

// Assign a buffer

Char szcaptionbase [100];

// Copy the main window The title into the buffer and add "[View 1]".

STRCPY (SzcaptionBase, (WMAINWINDOW. * PFNWGC) ());

STRCAT (SZCAPTIONBASE, "[View 1]");

// Set sub-window title

(PWCHILDWINDOW -> * PFNWSC) (SzcaptionBase)

Member pointer

Limit the address of a static member is not a member pointer, which is a rule pointer for a static member instance. However, all objects of a given class have only a static member instance, and the ordinary gating (&) and indirect reference (*) operators can be used.

Member pointer and virtual function

Calling a virtual function via a member pointer function is like a function that is directly called: The correct function looks up and calls in the V table. The following code shows how this is completed:

Class Base

{

PUBLIC:

Virtual void print ();

}

Void (Base :: * bfnprint) () = & base :: print;

Void Base :: Print ()

{

COUT << "Print function for class 'base' / n";

}

Class Derived: Public Base

{

Public: void print (); // Print is also a virtual function

}

void derived :: print ()

{

Cout << "Print function for class 'derived' / n;

}

void main ()

{

Base * bptr;

Base bobject;

Derived dobject;

BPTR = & bobject; // Set pointer to the address pointing to BOBJECT

(BPTR -> * bfnprint) ();

BPTR = & DOBJECT; / / Set pointer to the address of DOBJECT

(BPTR -> * bfnprint) ();

}

The output of the program is:

Print Function for Class 'Base'

Print Function for Class 'Derived'

The key to virtual function work, and usually, it is called by pointers to a base class (see Chapter 9 "Derivation Class" in Chapter 9).

Use inheritance representation class member pointer

The class member pointer affects the size and speed of the class member pointer before class definition. Represents the number of bytes and interpretation required by a class member pointer depending on whether the class is defined as without, with single and multiple or virtual inheritance.

All in all, the more complex the inheritance of the class, the more the number of bytes required for the class member pointer, the greater the code required to explain the pointer.

If you need to explain a class member pointer before class definition, you must use the / vmg command line option, or use the relevant Pointers_TO_MEMBERS to compile instructions, or you can use __single_inheritance, __ multiple_inheritance or __virtual_inheritance keyword specified in the class description The inheritance of use is thus allowed to generate the control of the code on each class. These options are explained below. Note: If you always explain a class member pointer after the class definition, you don't need to use any of these options.

Microsoft may intend to optimize the representation and generation of the member pointer by selecting the most compact representation. This requires that the member pointer is based on the place where the member pointer is illustrated. Pointers_to_members Compile Indicates that this limit is allowed, and the code required for the pointer size and interpretation pointer is controlled.

grammar

#pragma pointers_to_members (pointer description, [most common representation])

The pointer descriptions are specified whether a member pointer is indicated before or after the relevant function definition. The pointer description parameters can be full_generality or best_case.

The most common representation of the specified compiler is securely used to reference the minimum pointer representation of any class member pointer in a conversion unit. This parameter can be SINGLE_INHERITANCE, MULTIPLE_INHERITANCE or Virtual_inheritance. Pointers_to_members with Best-Case parameters Compile indication is the default value of the compiler, if you always define a class before you describe a class member pointer, you can use this default. When the compiler encounters a description of a class member pointer, it has known the type of inheritance used. Thus, the compiler can use the minimum representation of the pointer and generate the minimum amount of code required for each inheritance to operate on the pointer. This is equivalent to the representation of the optimal situation to specify the optimal situation in the command line to use all the classes in the conversion unit.

If you need to explain a class member pointer before defining a class, use the Pointers_to_members with full_generality parameters (if you define members in two different classes and use the member pointer to each other, it will cause this need. A class must be referenced before it is defined by each other. The compiler uses the most universal representation of the member pointer. This is equivalent to the / VMG compiler option. If you specify full_generality, you must also specify Single_inheritance, Multiple_inheritance or Virtual_inheritance. This is equivalent to using the / VMG compiler option using the belt / VMS, / VMM or / VMV option.

Pointers_to_members compile instructions (/ VMS option and / VMG option together) with full_generadation parameters (/ VMS option and / vmg option) Specify the most common representation of the class member pointer is the use of no inheritance or single inheritance. This is the minimum representation of class member pointers. If a member pointer is explained in the genre, the inheritance mode is multiple inheritance or virtual inheritance, the compiler generates an error. For example, will the following statement:

#pragma pointers_to_members (full_generality, single_inheritance) Before placing a class definition, explain that all class definitions are only inherited. Once specified, compiling the specified option cannot be changed by using the Pointers_to_members.

Pointers_to_members with full_generality, multiple_inheritance parameters (/ VMM option and / vmg option together) Specify the most universal representation of the class member pointer is the kind of inheritance. This indicator is much larger than the inheritance. If a member pointer is illustrated by the type definition of the class definition of a virtual inheritance, the compiler generates an error.

Pointers_to_members with full_generality, Virtual_inheritance parameters (/ VMV option and / vmg option together) Specify the most common representation of the class member pointer is the kind of virtual inheritance. This is the most expensive option based on the size of the pointer and the code required by the pointer. However, this option never generates an error, and when the ful_generality parameter is specified to the Pointers_to_members or / vmg command line option, it is a default.

grammar

The equivalent language structure uses this syntax: class description:

Class inheritance type OPT class name;

Inherit type:

__single_inheritance

__multiple_inheritance

__virtual_inheritance

As shown in this example:

Class __single_inhertance s;

INT S :: P;

Regardless of the compiler option or compile instruction, the members of the class S will use the minimum possible representation.

You can also explicitly give a forward description represented by a member pointer representative of the preceding description.

Note: The same forward description represented by the class member pointer should appear in each conversion unit of the member pointer of that class, and the description should appear before the member pointer is illustrated.

Array

An array is a collection of similar objects. The simplest case of an array is a vector. C provides a convenient syntax for a fixed size array:

grammar

Description Indicator DNAME [constant expression OPT];

The number of elements in the array is given by a constant expression. The first element of the array is Element No. 0, and the last element is the (N-1) element, where n is the size of the array. A constant expression must be an integer and must be greater than 0. An 0-size array is only legitimate when an array is a Struct or Union's last domain, and the Microsoft Expansion (/ ZE) is legal.

An array is a derived type, so it can be constructed from any other derived or basic type other than the VOID.

An array constructed from other arrays is a multi-dimensional array. These multi-dimensional arrays are specified in order of multiple [constant expressions], for example, consider this description:

INT I2 [5] [7];

It specifies an Int type array, conceptually arranged in a two-dimensional matrix in a 5 row of 7 columns, as shown in Figure 7.2.

In the multi-dimensional array description of the initializer table (such as described in the initializer), the constant expression of the first dimension specified boundary can be omitted. E.g:

Const int cmarkets = 4;

/ / Describe a floating point type indicates transportation costs

Double TransportCosts [] [cmarkets] =

{{32.19, 47.29, 31.99, 19.11},

{11.29, 22.49, 33.47, 17.29},

{41.97, 22.09, 9.76, 22.55}};

The above description defines an array of 3 rows of 4 columns; the line represents the factory, which is a market that the factory is transported, and the value is from the factory to the market transportation fee. The first dimension of the array is omitted, but the compiler fills it by checking the initializer.

The technique specified by the first dimensional boundary of the multi-dimensional array can also be used in the function description, as shown below:

#include

/ / Including DBL_MAX

#include

Const int cmkts = 4;

/ / Describe a floating point type indicates transportation costs

Double TransportCosts [] [cmkts] =

{

{32.19, 47.29, 31.99, 19.11},

{11.29, 22.49, 33.47, 17.29},

{41.97, 22.09, 9.76, 22.55}

}

// Calculate the size of the undetemted dimension

Const int cFactories = Sizeof TransportCosts /

SizeOf (double [cmkts]);

Double FindMintomkt (int Mkt, Double Transportcosts [CMKTS], INT CFACTS;

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

{

Double mincost;

Mincost = findmintomkt (* Argv [1] - '0', TransportCosts, CFACTS;

COUT << "The minimum cost to market" << argv [1] << "IS:"

<< mincost << "/ n";

}

Double Findmintomkt (int Mkt, Double Transportcosts [] [CMKTS], INT CFACTS)

{Double Mincost = DBL_MAX; for (INT i = 0; i

Mincost = (Mincost

Return mincost;

}

The function FindMintomkt is written into add new plants, and does not need to change any code as long as it is recompiled again.

Use array

A single element in the array uses an array subscript operator ([]) to access. If a single-dimensional array is used in an expression that does not have a subscript, the array name evaluates a pointer to the first element of the array. E.g:

Char Charray [10];

... char * pch = charray; // Pointer to the first element

Char ch = charray [0]; // The value of the first element

CH = Charray [3]; // The value of the fourth element

When using a multi-dimensional array, various combinations are accepted. The following example illustrates this: Double Multi [4] [4] [3]; // Describes an array

Double (* p2multi) [3];

Double (* p1multi);

COUT << Multi [3] [2] [3] << "/ n"; // use three subscripts

P2Multi = Multi [3]; // Make P2Multi points to the fourth "plane" of Multi

P1MULTI = MULTI [3] [2]; // makes P1Multi points to the fourth "plane" of Multi,

// Multi's second line

In the above code, MUTLI is a three-dimensional array of Double types. P2Multi pointer points to an array of a Double type size 3. In this case, 1, 2, and 3 subscripts. Although all subscripts are usually specified, such as in the COUT statement, a particular subset of the array element is sometimes selected, as shown by subsequent statements.

Array in the expression

When an array type identifier is now in an expression rather than in the initialization of SIZEOF, addresses (&), or reference, it is converted to a pointer to the first element of the array, for example:

Char szerror1 [] = "Error: Disk Drive Not Ready."; char * psz = szerror1;

The PSZ pointer points to the first element of the array szerror1. Note that the array is not like a pointer, an array is an unmodified L value. Therefore, the following assignment is illegal:

Szerror1 = PSZ;

Interpretation of the subscript operator

Like other operators, the subscript operator ([]) can be redefined by the user. If it is not overloaded, the default action of the subscript operator is to use the following methods to combine array and subscript:

* ((Array name) (subscript))

As in all additions to the pointer type, the positioning is automatically executed to adjust the size of the type. Therefore, the result value is not the number of subscripts from the array name, but the elements of the following marked order (more information about this conversion "adding operators in Chapter 4" Expression " ").

Similarly, for multidimensional arrays, the address is derived using the following method:

* ((Array name) (subscript 1 * max2 * max3 ... MAXN)

Subscript 2 * max3 ... MAXN)

... subscript n))))

Indirect operation on the array type

An N-1 Dimensional array is generated using an indirect operator (*) on an N-dimensional array type. If N is 1, a scalar (or array element) is generated.

Array sort

The C array is sorted in the main order. The order of the main order means that the final subscript is the fastest.

Function description

This section includes the following topics:

* Function Description Syntax

· Variable parameter table

· Explain a function without parametrism

· Function overload

· Restriction on functions

· Pass instructions

· Parameter table in function prototype (undefined instruction)

· Parameter table in function definition

* Default parameters

· By default parameter expressions

· Other considerations The function definition is included in the Function Definition section.

Function instructions French

Method

Indicator DNAME (Parameter Description Table) CV Modification Table OPT

Pass instructions:

Parade accounting table, ...

Pass instructions:

Parameter description

Parameter instructions, parameter description

Pass instructions:

Description indicator

Description Indicator Description = Expression Description Indicator Abstract Indicator OPT

Description Indicator Abstract Indicator OPT = Expression

The identifier given by the DNAM has a type "CV modified table function, with the parameter instruction table and return type description indicator".

Note that const, volatile, and many Microsoft special keywords can appear in the description of the CV modifier table and name. The following example gives two simple functions description:

Char * Strchr (Char * Dest, Char * SRC);

Static int atoi (const char * ascnum) const;

The following grammar explains the details of the function description:

grammar

Pass instructions:

Parade Table Opt ... OPT

Parameter instruction table,

... Parameter Description Table:

Parameter description

Parameter instructions, parameter description

Participation description:

Description indicator

Description indicator specifier, expression

Description Indicator Abstract Indicator OPT

Description Indicator Abstract Indicator OPT, Expression

Variable parameters

The last member of the Table Parts Description Table is the omitting number (...), which indicates a variable number of variable numbers. In these cases, C provides type checks for explicitly descriptions. When you need a common function, the number and type of the parameters are variable, you can use a variable parameter table. The Printf function cluster is a function example of using a variable parameter table.

To access the parameters after those description, use the macros included in the standard containing files stdarg.h, as described in this chapter "Function with variable parameters".

Microsoft Special Office

Microsoft C allows the omitted number to be specified as a parameter, if the omitted number is the first parameter and the foregoing number is a comma. Therefore, Int Func (INT i, ...) is explained; it is legal, but int func (inti ...);

Microsoft End

Function with variable variable parameters Description requires at least one "position occupant" parameter, even if it is not used. If this placeholder parameter is not provided, there is no way to access the remaining parameters.

When the CHAR type is passed as a variable parameter, they are converted to an int type. Similarly, when the parameter of the Float type is passed as a variable parameter, they are converted into a Double type. Other types of parameters belong to commonly used integers and floating points. See Chapter 3 "Integral Lifting" in Chapter 3, "Standard Conversion".

Explain a function without a parameter

In the parameter note table, use a single keyword void instructions without a parameter as long as the keyword Void is the first and is a member in the table. VOID type parameters in any other location in the parameter note table will generate an error. E.g:

Long gettickcount (void); //

Long gettickcount (int revSet, void); // error

Long gettickcount (void, int revSet); // error

In C , explicitly specify a function that a function does not require parameters is the same as that of a function that does not have a parameter indicating table, therefore, the following two statements are identical:

Long gettickcount (); long gettickcount (void); Note: In addition to this, other specified VOID parameters are illegal; but the type derived from the VOID type (such as pointer to Void and VOID array) can appear in parameters Describe any location in the table. The function overload C allows a function that specifies more than one identical name in the same range. These are called "overloaded functions", in detail in Chapter 12 "Overload". The overload function allows the programmer to provide different semantics for a function, depending on the type and number of parameters. For example, the Print function with a string (or char *) parameter is extremely different with a function with a Double type parameter. The overload allows unified naming to prevent programmers from to invent names such as Print_SZ or Print_D. Table 7.1 shows what part of C use function description is distinguished from a function group that has the same name in the same range.

Table 7.1 Override consideration

Function Description Element Used for Overload? Function Return Type Number of Number of Volumes is the type of parameter is the eailed number or does not appear to use the use of the TypeDef name whether the array is bound to whether const or volatile (in the CV modifier table) Yes

Although the function can be distinguished based on the return type, they cannot be overloaded on this basis.

The following example illustrates how the overload is used. Another way to solve this problem is given in the "default parameters" behind this chapter. #include

#include

#include

// Three Print function prototypes

INT Print (char * s); // Print a string

INT Print (double DVALUE); // Print a Double value

INT Print (Double Dvalue, Int PREC); / / Print a double value with a given accuracy

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

{

Const Double D = 893094.2987;

IF (Argc <2)

{

/ / These calls for printing Invoke Print (char * s)

"" This Program Requires One Argument. ");

Print ("The Argument Specifies The Number of");

Print ("Digits Precision for the Second Number);

Print ("Printed.");

}

// Call the Print (double DVALUE).

Print (d);

// Call Print (Double Dvalue, Int PREC).

Print (D, ATOI (Argv [1]));

}

// Print a string

Int Print (char * s)

{

Cout << s << endl;

Return cout.good ();

}

/ / Print a double number with default accuracy

INT Print (double Dvalue)

{

Cout << Dvalue << Endl;

Retarn cout.good ();

}

// Print a double number with the specified accuracy

// Positive precision indicates several digits of digital accuracy after the decimal point

/ / Negative accuracy indicates a rounded place to the left side of the decimal point

Int Print (Double Dvalue, INT PREC)

{

/ / Find a table for rounding or truncation

Static const double rgpow10 [] = {

10E-7, 10E-6, 10E-5, 10E-4, 10E-3, 10E-2, 1e-1, 10E0,

10E1, 10E2, 10E3, 10E4, 10E5, 10E6

}

Const int ipowzero = 6;

// If the accuracy is outside, then this number is printed.

IF (Prec <-6 || PREC> 7)

Return Print (DVALUE);

// Position, truncation, then position

DVALUE = floor (DVALUE / RGPOW10 [iPowzero-prec])]

* RGPOW10 [iPowzero-PREC];

Cout << Dvalue << Endl;

Return cout.good ();

}

The above code gives overloading of the Print function in the file range. See Chapter 12, "Overload" on how to overload restrictions and overloads affecting other C elements.

Limit function

You cannot return an array or function, but they can return references or pointers to argments or functions. Another way to return an array is to use that array as a member to explain a structure:

Struct Address

{

Char szaddress [31];

Address getaddress ();

Defining a type is illegal in the return type section of the function description or in any of the parameters of the function.

The following legal C code is illegal in C :

Enum weather {cloudy, rainy, sunny} getWeather (date today)

The above code is not allowed, because the Weather Type has a relative GetWeather part of the partial function range, and the return value is not suitable for use. Since the variety of the function has a function range, the description of the parameter table will have the same problem if it is not allowed. C does not support a function array. But the array of pointers pointing to the function may be very useful. In the syntax analysis of the class Pascal language, the code typically separates the lexical analyzer used in a language symbol analysis and a grammatical analyzer that attaches semantic symbols. If the analyzer returns a specific normal value for each symbol, the code can be written as shown in the following example to perform the appropriate processing:

INT processfortoken (Char * sztext);

INT ProsesSwhileToken (Char * Sztext);

INT ProcessBegintoken (Char * sztext);

INT ProcessendToken (Char * sztext);

INT processiken (char * sztext);

INT ProcessthenToken (Char * sttext);

INT ProcesselStoken (Char * sztext);

Int (* processtoken []) (char *) = {

Processfortoken, ProcessBegintoken, ProcessendToken, Processiftoken, ProcessthenTheken,

Processelsetoken};

const Int Maxtokentd = SizeOf Processtoken / SizeOf (int (*));

...

INT DoprocessToken (int tokenid, char * sztext)

{

IF (tokentd

Return (* processtoken [tokenid]) (sztext);

Else

Return Error (sztext);

}

Pass instructions

A function description of the parametric table part:

* Allows the type of parameter between the compiler's check function and the parameters provided in the call.

* Allows to convert from the supplied parameter type, conversion process, or implicit or user-defined. l Check the initialization or assignment of the function pointer.

* Check the initialization or assignment of the function reference.

Parameter table in function prototype (non-definition)

The parameter indicator form is a table of the type name of the parameter. Consider the reference to the function of FUNC, with three parameters: pointing to the pointer of char, CHAR and INT type.

The code for such a parameter indicator table is writable:

Char *, char, int

So function description (prototype) can be written:

Void Func (char *, char, int);

Although the above description contains enough information for compiler to perform type check and conversion, there is no more information on what is provided. A better way for a writing function description is to include the identifier because they will appear in the function definition, as shown below:

Void Func (Char * Sztarget, Char ChSearchchar, Int Nstartat);

These identifiers in the prototype are only useful for default parameters because they are directly out of range. But they provide meaningful program documentation.

Parameter table in function definition

The difference between the parameter table and the prototype in a function definition is only: if an identifier is present, it represents the formal parameter of the function. The identifier name does not need to match those in the prototype (if present).

Note: You can define a function with an unnamed parameter. But these parameters are inaccessible to their functions.

Default parameter

In many cases, the frequency used by the function has too small, and only one default is enough. To use this, the default parameters are only allowed to specify those parameters that are meaningful functions in a given call. In order to illustrate this concept, consider the examples given in the "Function Overload" in this chapter:

// Three Print function prototypes

INT Print (char * s); // Print a string

INT Print (double DVALUE); // Print a Double value

INT Print (Double Dvalne, Int PREC); // Print a Double value of a given precision can be provided with a reasonable default value in many applications without having to need two functions. // Two Print function prototype INT print (char * s); // Print a string

INT Print (double DVALUE, INT PREC = 2); // Print a given Double value Print function is slightly changed to reflect this fact: that is, there is only one such function for the Double type:

/ / Print a given Double value

/ / Positive precision value indicates how many numbers displayed after the decimal point

/ / Negative precision value indicates the position of the left side of the decimal point

Int Print (Double Dvalue, INT PREC)

{

/ / Use the lookup table for rounding or truncation

Static const double rgpow10 [] = {

10E-7, 10E-6, 10E-5, 10E-4, 10E-3, 10E-2, 10E-1, 10E0,

10E1, 10E2, 10E3, 10E4, 10E5, 10E6

}

Const int ipowzero = 6;

// If the accuracy is exceeded, then this number is printed.

IF (PREC> = - 6 || PREC <= 7)

// Position, truncation, then position

DVALUE = floor (DVALUE / RGPOW10 [iPowzero-prec]) *

RGPOW10 [iPowzero-PREC];

Cout << Dvalue << Endl;

Return cout.good ();

}

In order to call a new PRINT function, use the following code:

Print (d); // accuracy is 2, provided by the default parameters

Print (d, 0); // Remove the default parameters to obtain other values.

Pay attention to the following points when using default parameters:

* Default parameters are only used in function calls that are omitted in tail parameters, ie they must be the last parameter. Therefore, the following code is illegal:

INT Print (double DVALUE = 0.0, int prec);

* A default parameter cannot be defined later, even if the definition is completely identical. Therefore, the following code produces an error:

// Print function prototype

INT Print (Double Dvalue, Int PREC = 2); ...

// Print function definition

INT Print (Double Dvalue, Int PREC = 2)

{

...

}

The problem with this code is that the function in the definition description is defined for the prec.

* Additional default parameters can be added by the following description.

* You can provide default parameters for function pointers. E.g:

INT (* pshowintval) (INT i = 0);

Default parameter expression

Expression used by default parameters is usually constant expression, but this is not required. Expressions can combine functions, constant expressions, and global variables in the current range. Expression does not contain local variables or non-static class member variables.

The following code shows this:

Bool createvscrollbar (hwnd hwnd, short nwidth =

GetSystemMetrics (SM_CXVScroll);

The above description specifies a function to create a vertical scroll bar for a given width for a window. If a width parameter is not provided, the Windows API function getSystemMetrics is called to find the default width.

The default expression is obtained after the function call, but the value is completed before the function call actually occurs.

Since the function of the function is within the function range, and because the value of the default parameter occurs before entering this range, you cannot use the parameter or local variable in the default parameter expression.

Note Any shape reference in a default parameter expression hides a global name within a function range, which can cause errors. The following code is illegal:

Const int categories = 9;

Void Enum categories (char * categories [], int n = categories);

In the front code, the global name Categories are hidden within the function range, making the default parameter expression invalid. Other considerations

The default parameter is not considered part of the function type, so it is not used to select a function of the overload. If the two functions are different from the default parameters, they are considered a function of multiple definitions rather than overload.

The default parameters cannot be provided for operators for overload.

Function definition

Function definitions and function descriptions differ from them that they proceeded to the code of the function.

grammar

Function definition:

Description Indicator OPT Description CTOR Initializer OPT Function

Functional body:

The format of the syndrome in the syntax discussed in the "Function" is:

DNAME (Parameter Description Table) CV Modification Table OPT

The shape described in the parameter description table is within the range of the function.

Figure 7.3 shows the various parts defined by a function. The shaded area is a function body.

The CV modified CV modifier of the specifier indicates how to treat this pointer; it is only used with the class member function.

The CTOR initializer element in the syntax is only used in the constructor, and its purpose is to allow initialization of the base class and the included object (more information about the CTOR initializer "see Chapter 11" Special member functions " Initialization base class and member ").

Function with variable parameter table

A function requiring a variable table is described in a parameter table, as described in the "variable parameter table" in front of this chapter. To access parameters that use this method to pass to the function, use the stdarg.h standard to include the types and macros described in the file.

The following example gives how VA_START, VA_ARG, and VA_END macros and VA_List types (described in stdarg.h) work together.

#include

#include

// showVar instructions, but not defined

Int Showvar (char * sztypes, ...);

void main ()

{

Showvar ("FCSI", 32.4F, 'A', "Test String", 4);

}

// showVar with a format string in the form of "FCSI", where each character indicates that position

// Parameter type

//

// i = int

// f = float

// c = char

// s = string (char *)

//

// The following format Description is a N-parameter table, where n == strlen (SzTypes)

Void showvar (char * sztypes, ...)

{

VA_LIST VL;

INT I;

// sztypes is the final parameters specified; all other must be accessed using a variable parametric macro

VA_Start (VL, SZTYPES);

// Step through the list

For (i = 0; sztypes [i]! = '/ 0'; i)

{

Union printable_t

{

INT I;

Float f;

Char C;

Char * S;

}

PRINTABLE

Switch (SzTypes [i]) // expected type

{

Case 'I':

Printable.i = VA_ARG (VL, INT);

Printf ("% I / N", printable.i);

Break;

Case 'f':

Printable.f = VA_ARG (VL, FLOAT);

Printf ("% f / n", printable.f);

Break;

Case 'C':

Printable.c = VA_ARG (VL, CHAR);

Printf ("% f / n", printable.f);

Break;

Case 's':

Printable.s = VA_ARG (VL, CHAR *);

Printf ("% s / n", printable.s);

Break;

DEFAULT:

Break;

}

}

VA_END (VL);

}

The following example illustrates the following important concepts: l A table tag will have to establish a variable of a VA_List type before any variable parameters, in the previous example, the identifier is called VL. * Single parameters use the VA_ARG macro to access, the VA_ARG macro needs to be told to retrieve the type of parameters so that it can pass the correct number of bytes from the stack. If a different type of incorrect type with a call program is specified to VA_ARG, the result is unpredictable.

* The result of using the VA_ARG macro should be explicitly converted to the desired type

* VA_END macros must be called to terminate variable parameter processing.

Initializer

The specification can specify the initial value of the object. The only way to specify a value for the Const type object is to specify in the specifier. The portion specified in the specification This initial value is referred to as "initializer."

grammar

Initializer

= Assignment expression

= {Initializer table, OPT}

(Expression table)

Initializer table:

expression

Initializer table, expression

{Initializer table, OPT}

The initializer has two basic types:

* Initializer called using an equal signing.

* The initializer that is called in the form of function. The object only with a class of constructors can be initialized with a functional form syntax. Differences in two grammar formats are also the potential use of access control and temporary objects. Consider the following code, use the initializer to explain some explanatory characters:

INT i = 7; // Use an equal sign

Customer Cust ("TaxPayer, Joe", // Using Function Form Syntax

"14 cherry lane", // Constructor requirements

"Manteca",

"Ca");

Automatic, registers, static, and external variables can include an initializer. However, the instructions of the external variable can include the initializer only when the variable is not illustrated as extern.

These initializers can include constants and variables included within the current range. The initializer is evaluated in the program where the program flow is encountered, or the global static object and variable evaluates in the program (more information about the initialization of global static objects, see Chapter 2 "Basic Concept" " Additional start considerations ").

Initialization to the pointer to the Const object

A pointer to the Const object can be initialized with a pointer to a non-Const object, but it cannot be seen.

For example, the following initialization is legal:

Window StandardWindow;

Const Window * PStandard Window;

In the above code, the pointer PStandardWindow is illustrated as a pointer to a const object. Although StandardWindow is not illustrated as const, this instruction is acceptable because it is not allowed to be described as a Const object to access a const object. The opposite is as follows:

Const Window StandardWindow;

Window * pstandardWindow; STANDARDWINDOW

The above code Explicitly stanardWindow is a const object. Initializing the address of StandardWindow, the very amount of the pointer PStandardWind will generate an error because it allows the Const object to be accessed by the pointer, ie it allows the constative of the const attribute from the object.

Unexreed object

Objects and simple variables of Static storage classes not using the initializer are ensured that it is initialized to one bit mode 0. This special processing is not generated without initialized objects for automatic or register. They have undefined values.

Initialization static member

Static member initialization appears in the class range. Therefore, they can access other member data or functions. E.g:

Class Dialogwindow

{

PUBLIC:

Static short getTextheight ();

Private:

Static short nTextheight;

}

Short dialogwindow :: ntextheight = getTextHeight ();

Note that in the definition of NTEXTHEIGHT in front, GetTextHeight hides the DialogWindow :: GetTextHeight.

Initialization collection

A collection type is a set of such arrays, classes, or structural types:

* No constructor

* No non-public member

* No base class * No virtual function

The initializer of the collection can be specified as a comma-separated value table in the currency bracket. For example, this code illustrates an array of 10 INT and initializes:

Int rgiarray [10] = {9, 8, 4, 6, 5, 6, 3, 5, 6, 11};

The initializer is stored in an array element in an increasing subscript order. Therefore, Rgiarray [0] is 9, Rgiarray [1] is 8, and the like until Rgiarray [9] is 11. To initialize a structure, use this code:

Struct rcprompt

{

Short nrow;

Short ncol;

CHAR * SZPROMPT;

}

RcPrompt rccontinueyn = {24, 0, "continuous (y / n?)};

Collection of initializer table length

If a set initializer table is shorter than the array or class type that is being initialized, 0 is not specified in the element. Therefore, the following two instructions are equivalent: // Explicitly initialize all elements

INT RGIARRAY [5] = {3, 2, 0, 0, 0};

// Allow the reserved element to initialize

Int rgiarray [5] = {3,2}

As seen, the initializer can be truncated, but there is too much initializer will generate an error.

Initialization contains collection

Collection Certain collections include other collections, such as arrays, structural arrays, or structures consisting of other structures, to provide each initialization of each initialization by using a curly-proof table Initializer, for example:

// Describe an array of RCPROMPT types

RcPrompt Rgrcprompt [4] =

{{4, 7, "Options are:"},

{6, 7, "1. Main menu"},

{8, 7, "2. Print Menu"},

{10, 7, "3. File Menu"}};

Note that RGRCPROMPT is initialized by the lacexic brackets surrounded by the curly brackets. The closed curly bracket is not a grammar, but they make the description clearer, the following procedure shows how a two-dimensional array is filled with such an initializer:

#include

void main ()

{

INT RGI [2] [4] = {1, 2, 3, 4, 5, 6, 7, 8};

For (int i = 0; i <2; i)

For (int J = 0; j <4; j)

COUT << "RGI [" << i << "] [" << j << "] ="

<< RGI [i] [j] << endl;

}

The output of the program is:

RGi [0] [0] = 1

RGi [0] [1] = 2

RGI [0] [2] = 3

RGI [0] [3] = 4

RGi [1] [0] = 5

RGi [1] [1] = 6

RGi [1] [2] = 7

RGi [1] [3] = 8

The short initialization table is only available when the explicit sub-set initializer is inserted and is bracketing. If RGI is description:

INT RGI [2] [4] = {{1, 2}, {3, 4}};

The output of the program will be:

RGi [0] [0] = 1

RGi [0] [1] = 2

RGi [0] [2] = 0

RGi [0] [3] = 0

RGi [1] [0] = 3

RGi [1] [1] = 4

RGI [1] [2] = 0

RGi [1] [3] = 0

Incomplete type initialization

Incomplete type, such as the array type of the boundary, can be initialized as follows:

Char Homeow [] = {'a', 's', 'd', 'f', 'h', 'I', 'K', 'L'}

The compiler calculates the size of the array from the number of initializer supplies.

Incomplete type, as indicated but undefined pointing pointers, which are described below:

Class Definedelsewhere; // Class definitions

Class Definedhere

{

... Friend Class Definedelsewhere;

}

Use constructor initialization

Class type objects initialize by calling the appropriate constructor of the class. See Chapter 11, "Explicit Initialization" in Chapter 11, "Special Member Function".

Initializer and joint

The UNION type object is initialized with a single value (if there is no constructor). This is done by one of these two methods:

* Initialize the combination with another object of the same UNION type, for example:

Struct Point

{

Unsigned x;

Unsigned y;

}

Union PTLONG

{

Long L;

Point pt;

}

...

PTLONG PTORIIN;

PTLONG PTCurrentt = Ptorigin;

In the above code, PTCurrent initializes an object of the same type as the PTORIGIN value.

* Joints the first member to initialize the initializer enclosed by the curly braces. For example: ptlong ptcurrent = {0x0A000Al};

Initialization character array

The character array can be initialized by one of the following two methods:

* Single place, such as:

Char chabcd [4] = {'a', 'b', 'c', 'd'};

* Use a string, such as;

Char chabcd [5] = "abcd";

In the second case, that is, the character number is initialized with a string, and the compiler adds the '/ 0' of the tail (string end character). Therefore, the array must be at least a large number of characters in the string.

Because most string processing uses a standard library function or dependent on the end of the end of the character, the unlimited array initializes the unlimited boundary is as follows:

CHAR Chabcd [] = "abcd";

Initialization reference

The type variable reference must be initialized with derived reference type objects or converted to the derived reference type party. E.g:

INT IVAR; long lvar;

Long & longref1 = lvar; // No conversion

Long & Longref2 = Ivar; // Error

Const longref3 = Ivar; //

LongRef1 = 23L; // Change LVAR through a reference

LongRef2 = 11L; // Change Ivar through a reference

Longref3 = 11L; // error

Using a temporary object to initialize a unique way to initialize a constant temporary object. Once initialized, a reference type variable always points to the same object; it cannot be changed to another object.

Although the syntax can be the same, the initialization of the reference type variable and the assignment of the reference type variable are semantically different. In the previous example, changing the assignment of IVAR and LVAR looks similar to initialization, but there is a different effect. Initialization Specifies the object to which the reference type variable points points, assigns the value to the object being directed by reference.

Because the parameter passed to a reference type and returns a reference type value from a function is initialized, the formal parameter of the function is correctly initialized, as returned.

The reference type variable can be initialized without the initializer only in the following cases:

* Function Description (prototype). E.g:

INT func (int ";

* Function Return Type Description, for example:

INT & FUNC (INT &);

* Reference description of type class members, for example:

Class C

{

PUBLIC:

INT & I;

}

* Description of variables that are explicitly specified as extern, for example:

Extern Int & IVal;

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

New Post(0)