tailieunhanh - Thinking in C++ 2nd edition Volume 2 Standard Libraries & Advanced Topics revision 1 phần 8
bị buộc phải sử dụng một dàn diễn viên), và dàn diễn viên tất cả các cái nhìn khác nhau, vì vậy bạn không thể biết nếu bạn đã tìm kiếm cho mỗi một. Để giải quyết vấn đề này, C + + cung cấp một cú pháp đúc phù hợp bằng cách sử dụng các từ dành riêng: | being forced to use a cast and the casts all look different so you can t know if you ve searched for every one. To solve this problem C provides a consistent casting syntax using four reserved words dynamic_cast the subject of the first part of this chapter const_cast static_cast and reinterpret_cast. This window of opportunity opened up when the need for dynamic_cast arose - the meaning of the existing cast syntax was already far too overloaded to support any additional functionality. By using these casts instead of the newtype syntax you can easily search for all the casts in any program. To support existing code most compilers have various levels of error warning generation that can be turned on and off. But if you turn on full errors for the explicit cast syntax you can be guaranteed that you ll find all the places in your project where casts occur which will make bug-hunting much easier. The following table describes the different forms of casting static_cast For well-behaved and reasonably well-behaved casts including things you might now do without a cast . an upcast or automatic type conversion . const_cast To cast away const and or volatile. dynamic_cast For type-safe downcasting described earlier in the chapter . reinterpret_cast To cast to a completely different meaning. The key is that you ll need to cast back to the original type to use it safely. The type you cast to is typically used only for bit twiddling or some other mysterious purpose. This is the most dangerous of all the casts. The three explicit casts will be described more completely in the following sections. Summary RTTI is a convenient extra feature a bit of icing on the cake. Although normally you upcast a pointer to a base class and then use the generic interface of that base class via virtual functions occasionally you get into a corner where things can be more effective if you know the exact type of the object pointed to by the base pointer and that s what RTTI provides. Because .
đang nạp các trang xem trước