• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            S.l.e!ep.¢%

            像打了激速一樣,以四倍的速度運(yùn)轉(zhuǎn),開心的工作
            簡(jiǎn)單、開放、平等的公司文化;尊重個(gè)性、自由與個(gè)人價(jià)值;
            posts - 1098, comments - 335, trackbacks - 0, articles - 1
              C++博客 :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

            C++:Type Casting

            Posted on 2010-10-08 14:08 S.l.e!ep.¢% 閱讀(796) 評(píng)論(0)  編輯 收藏 引用 所屬分類: C++
            Converting an expression of a given type into another type is known as ? type-casting . We have already seen some ways to type cast:

            Implicit conversion

            Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. For example:

            														
            																short
            														 a=2000;
            int b;
            b=a;
            

            Here, the value of?a?has been promoted from?short?to?int?and we have not had to specify any type-casting operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short?to?int,?int?to?float,?double?to?int...), to or from?bool, and some pointer conversions. Some of these conversions may imply a loss of precision, which the compiler can signal with a warning. This can be avoided with an explicit conversion.

            Implicit conversions also include constructor or operator conversions, which affect classes that include specific constructors or operator functions to perform conversions. For example:

            														
            																class
            														 A {};
            class B { public: B (A a) {} };
            
            A a;
            B b=a;
            

            Here, a implicit conversion happened between objects of?class A?and?class B, because?B?has a constructor that takes an object of class?A?as parameter. Therefore implicit conversions from?A?to?B?are allowed.

            Explicit conversion

            C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion. We have already seen two notations for explicit type conversion: functional and c-like casting:

            														
            																short
            														 a=2000;
            int b;
            b = (int) a;    // c-like cast notation
            b = int (a);    // functional notation

            The functionality of these explicit conversion operators is enough for most needs with fundamental data types. However, these operators can be applied indiscriminately on classes and pointers to classes, which can lead to code that while being syntactically correct can cause runtime errors. For example, the following code is syntactically correct:

            														
            																// class type-casting
            														
            														
            																#include <iostream>
            														
            														
            																using
            														
            														
            																namespace
            														 std;
            
            class CDummy {
                float i,j;
            };
            
            class CAddition {
            	int x,y;
              public:
            	CAddition (int a, int b) { x=a; y=b; }
            	int result() { return x+y;}
            };
            
            int main () {
              CDummy d;
              CAddition * padd;
              padd = (CAddition*) &d;
              cout << padd->result();
              return 0;
            }
            
            												

            The program declares a pointer to?CAddition, but then it assigns to it a reference to an object of another incompatible type using explicit type-casting:

            padd = (CAddition*) &d;
            

            Traditional explicit type-casting allows to convert any pointer into any other pointer type, independently of the types they point to. The subsequent call to member?result?will produce either a run-time error or a unexpected result.

            In order to control these types of conversions between classes, we have four specific casting operators:?dynamic_cast,?reinterpret_cast,?static_cast?and?const_cast. Their format is to follow the new type enclosed between angle-brackets (<>) and immediately after, the expression to be converted between parentheses.

            dynamic_cast <new_type> (expression)
            reinterpret_cast <new_type> (expression)
            static_cast <new_type> (expression)
            const_cast <new_type> (expression)

            The traditional type-casting equivalents to these expressions would be:

            (new_type) expression
            new_type (expression)

            but each one with its own special characteristics:

            dynamic_cast: 轉(zhuǎn)換子類的指針(或引用)為父類的指針(或引用)

            dynamic_cast?can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.

            Therefore,?dynamic_cast?is always successful when we cast a class to one of its base classes:

            														
            																class
            														 CBase { };
            class CDerived: public CBase { };
            
            CBase b; CBase* pb;
            CDerived d; CDerived* pd;
            
            pb = dynamic_cast<CBase*>(&d);     // ok: derived-to-base
            pd = dynamic_cast<CDerived*>(&b);  // wrong: base-to-derived

            The second conversion in this piece of code would produce a compilation error since base-to-derived conversions are not allowed with?dynamic_cast?unless the base class is polymorphic.

            When a class is polymorphic,?dynamic_cast?performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class:

            														
            																// dynamic_cast
            														
            														
            																#include <iostream>
            														
            														
            																#include <exception>
            														
            														
            																using
            														
            														
            																namespace
            														 std;
            
            class CBase { virtualvoid dummy() {} };
            class CDerived: public CBase { int a; };
            
            int main () {
              try {
                CBase * pba = new CDerived;
                CBase * pbb = new CBase;
                CDerived * pd;
            
                pd = dynamic_cast<CDerived*>(pba);
                if (pd==0) cout << "Null pointer on first type-cast" << endl;
            
                pd = dynamic_cast<CDerived*>(pbb);
                if (pd==0) cout << "Null pointer on second type-cast" << endl;
            
              } catch (exception& e) {cout << "Exception: " << e.what();}
              return 0;
            }
            
            Null pointer on second type-cast
            

            Compatibility note:?dynamic_cast?requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using?dynamic_cast?to work properly.

            The code tries to perform two dynamic casts from pointer objects of type?CBase*?(pba?and?pbb) to a pointer object of type?CDerived*, but only the first one is successful. Notice their respective initializations:

            CBase * pba = new CDerived;
            CBase * pbb = new CBase;
            

            Even though both are pointers of type?CBase*,?pba?points to an object of type?CDerived, while?pbb?points to an object of type?CBase. Thus, when their respective type-castings are performed using?dynamic_cast,?pba?is pointing to a full object of class?CDerived, whereas?pbb?is pointing to an object of class?CBase, which is an incomplete object of class?CDerived.

            When?dynamic_cast?cannot cast a pointer because it is not a complete object of the required class -as in the second conversion in the previous example- it returns a null pointer to indicate the failure. If?dynamic_cast?is used to convert to a reference type and the conversion is not possible, an exception of type?bad_cast?is thrown instead.

            dynamic_cast?can also cast null pointers even between pointers to unrelated classes, and can also cast pointers of any type to void pointers (void*).

            static_cast: 指針的轉(zhuǎn)換: 1. 子類和父類之間指針互相轉(zhuǎn)換(不進(jìn)行安全檢查). 非指針的轉(zhuǎn)換: 2. 標(biāo)準(zhǔn)隱式轉(zhuǎn)換(如int->float, double->int). 3. 用戶定義轉(zhuǎn)換(構(gòu)造函數(shù)轉(zhuǎn)換,轉(zhuǎn)換函數(shù))

            static_cast ? can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of ? dynamic_cast ? is avoided.

            														
            																class
            														 CBase {};
            class CDerived: public CBase {};
            CBase * a = new CBase;
            CDerived * b = static_cast<CDerived*>(a);
            

            This would be valid, although?b?would point to an incomplete object of the class and could lead to runtime errors if dereferenced.

            static_cast?can also be used to perform any other non-pointer conversion that could also be performed implicitly, like for example standard conversion between fundamental types:

            														
            																double
            														 d=3.14159265;
            int i = static_cast<int>(d); 
            

            Or any conversion between classes with explicit constructors or operator functions as described in "implicit conversions" above.

            reinterpret_cast: 1. 任何指針之間的相互轉(zhuǎn)換,即使這些類型之間沒(méi)有任何關(guān)系. 2. 指針和整數(shù)類型的相互轉(zhuǎn)換(指針->int時(shí)在Mac上會(huì)報(bào)錯(cuò): loses precision).

            reinterpret_cast ? converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.

            It can also cast pointers to or from integer types. The format in which this integer value represents a pointer is platform-specific. The only guarantee is that a pointer cast to an integer type large enough to fully contain it, is granted to be able to be cast back to a valid pointer.

            The conversions that can be performed by?reinterpret_cast?but not by?static_cast?have no specific uses in C++ are low-level operations, whose interpretation results in code which is generally system-specific, and thus non-portable. For example:

            														
            																class
            														 A {};
            class B {};
            A * a = new A;
            B * b = reinterpret_cast<B*>(a);
            

            This is valid C++ code, although it does not make much sense, since now we have a pointer that points to an object of an incompatible class, and thus dereferencing it is unsafe.

            const_cast: 轉(zhuǎn)換對(duì)象(primitive類型的不可以: int, float, double...),指針,引用的const屬性,有則去掉,沒(méi)有則加上

            This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter:

            														
            																// const_cast
            														
            														
            																#include <iostream>
            														
            														
            																using
            														
            														
            																namespace
            														 std;
            
            void print (char * str)
            {
              cout << str << endl;
            }
            
            int main () {
              constchar * c = "sample text";
              print ( const_cast<char *> (c) );
              return 0;
            }
            
            sample text
            

            typeid

            typeid ? allows to check the type of an expression:

            typeid (expression)

            This operator returns a reference to a constant object of type?type_info?that is defined in the standard header file?<typeinfo>. This returned value can be compared with another one using operators?==?and?!=?or can serve to obtain a null-terminated character sequence representing the data type or class name by using its?name()?member.

            														
            																// typeid
            														
            														
            																#include <iostream>
            														
            														
            																#include <typeinfo>
            														
            														
            																using
            														
            														
            																namespace
            														 std;
            
            int main () {
              int * a,b;
              a=0; b=0;
              if (typeid(a) != typeid(b))
              {
                cout << "a and b are of different types:\n";
                cout << "a is: " << typeid(a).name() << '\n';
                cout << "b is: " << typeid(b).name() << '\n';
              }
              return 0;
            }
            
            a and b are of different types:
            a is: int *
            b is: int  
            

            When?typeid?is applied to classes?typeid?uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object:

            														
            																// typeid, polymorphic class
            														
            														
            																#include <iostream>
            														
            														
            																#include <typeinfo>
            														
            														
            																#include <exception>
            														
            														
            																using
            														
            														
            																namespace
            														 std;
            
            class CBase { virtualvoid f(){} };
            class CDerived : public CBase {};
            
            int main () {
              try {
                CBase* a = new CBase;
                CBase* b = new CDerived;
                cout << "a is: " << typeid(a).name() << '\n';
                cout << "b is: " << typeid(b).name() << '\n';
                cout << "*a is: " << typeid(*a).name() << '\n';
                cout << "*b is: " << typeid(*b).name() << '\n';
              } catch (exception& e) { cout << "Exception: " << e.what() << endl; }
              return 0;
            }
            
            a is: class CBase *
            b is: class CBase *
            *a is: class CBase
            *b is: class CDerived
            

            Notice how the type that?typeid?considers for pointers is the pointer type itself (both?a?and?b?are of type?class CBase *). However, when?typeid?is applied to objects (like?*a?and?*b)?typeid?yields their dynamic type (i.e. the type of their most derived complete object: 真實(shí)的類型,即使子類對(duì)象使用的是父類的指針,但返回的子類的信息).

            If the type?typeid?evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value,?typeid?throws a?bad_typeid?exception.

            久久精品国内一区二区三区| 婷婷久久综合九色综合九七| 久久AV高潮AV无码AV| 久久天天日天天操综合伊人av| 精品一久久香蕉国产线看播放 | 亚洲第一永久AV网站久久精品男人的天堂AV | 色婷婷久久综合中文久久蜜桃av | 国产精品无码久久久久久| 99久久成人18免费网站| 久久人人爽人人爽人人片AV麻豆| 99久久精品国产一区二区| 欧美亚洲色综久久精品国产| 2020最新久久久视精品爱 | 亚洲va国产va天堂va久久| 国产精品久久99| 国产免费福利体检区久久| 亚洲人成无码网站久久99热国产| 久久男人Av资源网站无码软件| 久久精品国产秦先生| 欧美精品国产综合久久| 久久婷婷久久一区二区三区| 色老头网站久久网| 国产精品免费久久久久影院 | 久久国产精品成人免费| 99久久国产宗和精品1上映| 久久国产视屏| 久久r热这里有精品视频| 无码精品久久久久久人妻中字| 久久精品国产精品亚洲下载| 国产精品久久久久久福利漫画 | 无码八A片人妻少妇久久| 久久国产美女免费观看精品 | 开心久久婷婷综合中文字幕| 国产一级持黄大片99久久| 久久婷婷国产综合精品| 久久久久国产精品人妻| 久久亚洲AV成人无码| 伊人 久久 精品| 久久精品日日躁夜夜躁欧美| 精品久久久久久久久免费影院 | 天天躁日日躁狠狠久久|