With the popularization of C ++, the standardization has become an inevitable trend of C ++ development. This standard is developed by ANSI (American National Standards Institute, American Standards Institute) and ISO (International Standardization Organization.
Many new rules in ANSI rules are expanded to the original C ++. You can also choose not to use these new features. These new features include the keyword mutable and explicit.
Some modifications have great potential. Currently, ANSI rules encourage some programming methods and discard other programming methods. Although it won't give up support for older programming methods for a period of time, but there are some programming methods that will eventually be eliminated-this means the compiler will give warnings and suggest using new programming methods. Sooner or later, we will discard the support for these old methods.
Main changes to ANSI rules include:
(1) Loading Method of the new header file
In the ANSI/iso c ++ standard, a namespace named STD is defined and many classes are defined in this namespace.
For example, the old method loads the header file # include <iostream. h>
Change the new rule to # include <iostream>
Using namespace STD;
(2) execution time information rtti (run-time type inforamtion)
The rtti Chinese literal translation is the execution time information, that is, the type of the data to be identified during execution. For example, what type of template is applied to the discriminant template?
Before using typeid, you must include the header file named typeid. You can use typeid to identify the data type of a variable.
Int;
If (typeid (A) = typeid (INT) // determine whether the data type of A is int
......
Or get the data type name of the variable char * data_type = typeid (a). Name () // output the Data Type of
(3) type conversion
C language uses a type conversion operator in all cases. In the ANSI/iso c ++ standard draft, four types of conversion syntax are added, specifically, four types of conversion are required to replace the traditional type conversion. The new type conversion syntax can control programs more accurately and reduce the generation of program errors. The four new types of conversion operators are const_cast, dynamic_cast, reinteroret_cast, and static_cast.
Const_cast (remove the const attribute)
The const_cast operator is used to call functions that should be used without the const keyword. In other words, it is for the programmer to remove the const definition that is restricted to the const member function under special circumstances, so that it can change specific attributes.
Example: void display_num (double * P)
{
Printf ("The value is % 2.3f \ n", * P );
}
Const Double X;
Display_num (& X); // disallowed! C ++ rules prohibit such calls because a const pointer cannot be passed to a non-const type parameter.
Display_num (const_cast <double *> (& X); // convert & X from the const double * type to the double * type.
[Note]: When the const_cast operator is used, the data pointed to by the pointer must not be changed. If you use the const_cast operator and try to change the data pointed to by the pointer, the actual results will be unpredictable.
Const Double X = 17.5;
Double * P;
P = const_cast <double *> (& X );
* P = 33.2; // this operation is undefined!
Dynamic_cast (type detection during program running)
Among the four new operators, only dynamic_cast provides new functions. If the running time type information (rtti) is enabled, dynamic_cast can help you determine the exact type of the object to be pointed to at runtime. It is related to the typeid operator.
The reason why the dynamic_cast operator is useful is that a base class pointer can point to many different child types (derived classes), and can be transformed into a base class object to be restored to the original class. However, it is limited to type conversion of object pointers, rather than object variables.
Class B
{
Public:
Virtual void func1 (INT );
};
Class D: Public B
{
Public:
Void func2 (void );
};
Void process_ B (B * Arg)
{B * pb;
PB = dynamic_cast <D *> (ARG );
If (PB) // If Arg points to the object of the derived class D or Class D, the type conversion is successful.
Pb-> func2 ();
...
}
[Note]: when compiling a program of this type, you must set the C ++ language settings in the project. Otherwise, the compiler will have an error message and an execution error will occur. Click the project/setting option. After the project Setting dialog box appears, switch to the C/C ++ label and click the Enable run-time type information (rtti) check box.
Reinterpret_cast (Conversion pointer type)
The reinterpret_cast operator converts a pointer to another type. The new type of pointer can be unrelated to the old one. It is usually used to convert some non-standard pointer data types, such as converting void * To char *. It can also be used for type conversion between pointer and integer.
Char a_char = 'A', * CP = & a_char;
Void * VP;
Vp = CP;
Cout <* (reinterprt_cast, char *> (VP); // converts the VP type from void * To char * During output *
[Note]: The reinterpret_cast operator is potentially dangerous. Do not use it unless you have a good reason to use it. For example, it can convert an int * type pointer to a float * type pointer, but this can easily cause integer data to be incorrectly read.
Static_cast (convert to related object or pointer)
The static_cast operator can perform type conversion between related objects and pointer types. Related classes must be associated with each other through inheritance, constructor, or conversion function. The static_cast operator can also perform type conversion between numbers (original) types.
Generally, the static_cast operator is used to convert a type with a larger field width to a smaller type. When the conversion type is the original data type, this operation can effectively prevent the compiler from issuing a warning.
Long I = 17;
Short J = static_cast <short> (I );
Similarly, a pointer to a base class can be converted to a pointer of a derived class without any restrictions. Because the running status check is not executed, make sure that the actual data supports this type of conversion. This is similar to the dynamic_cast operator.
In other cases, the static_cast operator can be effectively used, but this is rare in most programs. For example, Class A defines a type conversion to Class B, and Class B defines a type conversion to the int type. An object of operation class A can be converted to the int type.
A oa;
Int I = static_cast <int> (static_cast <B> (OA ));
(4) other keywords
In addition to the preceding keywords, ANSI rules support mutable, explicit, and bool:
The mutable keyword is similar to the const_cast mentioned above. It changes the declaration of a member. You can modify a member even if the member is part of a const object.
The keyword "Explicit" indicates that the constructor cannot be converted.
The keyword bool defines a data type, which has only two values: true and false ).
Do not use mutable or explicit. In addition to bool data types, ansi c ++ adds two predefined constants true and false, which are equal to 1 and 0, respectively.
(5) templates and Exception Handling
Template and exception handling are two main features of C ++. Many compilers now support these two features, but earlier versions of C ++ do not. Compile a common class or function and add a special type to it. Therefore, the template technology can be reused by code.
In addition to using the keyword template to define a new template, ANSI rules also list the standard template library STL (Standard Template Library), which contains many common classes. The purpose of the design is to build the basic data structures and algorithms frequently used in programming into libraries that can be applied by programmers.
Exception Handling is an advanced technique used to respond to runtime errors and other events. It is better than the legacy C-library functions raise and signal. Exception Handling is an error handling mechanism provided by C ++. The so-called exception is the literal translation of exception, which means that the program is not expected, that is, when the program is executed normally, there is an unexpected situation.
There are two main types of exception handling mechanisms: the error detection block and the error processing block.
Try
{// Error Test Block
Throw (error type );
// If an error occurs, use the throw statement to output the error.
}
Catch (Error Type 1)
{// Error handling block}
Catch (Error Type 2)
{// Error handling block}
...
Catch (...) // If the preceding processing type is not listed, block processing will be processed accordingly
{// Error handling block}
The throw statement is not only a string that can only throw the error message, but also an object of the exception class. Therefore, you can create an exception class for exception handling, these classes help to handle program errors. In the C ++ standard, standard exception handling classes are formulated. They all inherit from the exception class, which declares constructors and destructor, but does not include member functions. This base class has two sub-classes (logic_error reports errors that cannot be executed; runtime_error reports invalid operations or incorrect results), each of which corresponds to a group of Common exceptions. The header file of the exception class is defined as the exception header file, and the header file of the logic_error and runtime_error class is defined as stdexcept. If you want to know the Exception error information, you only need to call the what member function of the exception object.
(6) scope of the variables in the IF statement
In ansi c ++, you can declare a variable in the IF statement. The scope of this variable is the entire if statement block.
If (Int J = 1)
{
Cout <j <Endl; // correct. J is defined.
}
J = 2; // error, J is out of scope
The most obvious use of this feature is to control the scope of the pointer returned by dynamic_cast. In the following program, the IF statement defines PD, so it is available only when dynamic_cast is successful.
If (D * Pd = dynamic_cast <Arg>)
{// Dynamic_cast returns a successful result only when Arg points to the D object.
// PD can be safely used in statements
}
Pd-> func2 (); // error! PD is out of scope
Because the conversion is successful (a non-null value is returned to PD), it is safe to use Pd in the if statement block. If PD is used outside the if statement block, an error occurs during compilation. In this way, the error can be corrected before the program is released. The consequence is that if only PD is defined in one place, the compiler will prevent it from being used outside the scope of the PD action, thus preventing errors at runtime.
(7) Overloading of functions with enumeration types
Ansi c ++ enhances the State declared as an enumeration type. In particular, when a function is overloaded, The enum type can be distinguished from other integer types. In the earlier versions of C and C ++, The enum type and INT type parameter declarations can be exchanged.
Enum suit
{Clubs, diamonds, hearts, spades
};
Void func1 (int n)
{Cout <"inside func1 (INT)" <Endl;
}
Void func1 (Enum card)
{Cout <"inside func1 (suit)" <, Endl;
}
Function call: func1 (spades );
Output: Inside func1 (suit)
(8) Forward reference of embedded classes
C ++ allows class Pre-definition. Ansi c ++ extends this function to nested classes.
Class family
{
Class father; // allows forward reference to Father
Char last_name [5];
...
Class father // embedded class declaration
{
Char first_name [10];
...
};
};