C ++ syntax casts a small note ---

Type Conversion
  • C ++ contains two main types of conversion:

    • Implicit type conversion

      • Small type to large type conversion

        • char -> int

        • short ->int

        • int -> unsigned int

        • int -> float

        • float ->double

    • Display type conversion

      • const_cast: const attribute to remove variables

      • static_cast: completion of basic data types, the same type inheritance hierarchy of the conversion, the conversion between any type of null pointer type void *

      • dynamic_cast: polymorphic scenes, inheritance, has virtual functions, when used downcast

      • reinterpret_cast: changing a pointer or reference type, I do not know which type to use for converting it

  • Conversion between common type and class type, class type conversion between

    • Conversion constructors: The other class type to type

      • A special constructor

      • Only one parameter

      • It can be restricted using explicit constructor implicit type conversion

    • Type conversion functions: to convert other types of class type

    • The member functions as a type conversion functions, such as: int toNumber ()

    • When both defined conversion type conversion functions and constructors, the compiler error approach:

      • A conversion constructor class definition, a class definition class type conversion function, convert two ways, when the compiler error

      • Declare the constructor as explicit

      • As with the type int toNumber () member function in place type conversion function

 

. 1 #include <the iostream>
 2 #include < String >
 . 3  
. 4  the using  namespace STD;
 . 5  
. 6  class the Test
 . 7  {
 . 8      int mi The;
 . 9  public :
 10      the Test ( int I = 0 )   // conversion constructor 
. 11      {
 12 is          mi The = I ; 
 13 is      }
 14      
15      int toInt () // member function as a type conversion function 
16      {
 . 17          returnmi The;
 18 is      }
 . 19      
20 is      operator  int () // type conversion function 
21 is      {
 22 is          return mi The;
 23 is      }
 24  };
 25  
26 is  int main ()
 27  {   
 28      the Test T;
 29      
30      T = . 1 ; // compiler implicitly formula calls into the constructor 
31 is      
32      int X = T; // compiler implicitly call type conversion function 
33 is      
34 is      int Y = t.toInt (); // explicit call to a member function 
35      
36      return 0;
37 }

 

Guess you like

Origin www.cnblogs.com/chusiyong/p/11311113.html