Thinking in Cplus plus (P27)

Tham khảo tài liệu 'thinking in cplus plus (p27)', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | want to know the exact type it is pointing to you must dereference the pointer. For example if s is a Shape cout typeid s .name endl will print out the type of the object s points to. You can also ask a typeinfo object if it precedes another typeinfo object in the implementation-defined collation sequence using before typeinfo which returns true or false. When you say if typeid me .before typeid you . you re asking if me occurs before you in the collation sequence. The second syntax for RTTI is called a type-safe downcast. The reason for the term downcast is again the historical arrangement of the class hierarchy diagram. If casting a Circle to a Shape is an upcast then casting a Shape to a Circle is a downcast. However you know a Circle is also a Shape and the compiler freely allows an upcast assignment but you don t know that a Shape is necessarily a Circle so the compiler doesn t allow you to perform a downcast assignment without using an explicit cast. You can of course force your way through using ordinary C-style casts or a C static_cast described at the end of this chapter which says I hope this is actually a Circle and I m going to pretend it is. Without some explicit knowledge that it is in fact a Circle this is a totally dangerous thing to do. A common approach in vendor-defined RTTI is to create some function that attempts to assign for this example a Shape to a Circle checking the type in the process. If this function returns the address it was successful if it returns null you didn t have a Circle . The C RTTI typesafe-downcast follows this attempt-to-cast function form but it uses very logically the template syntax to produce the special function dynamic_cast. So the example becomes Shape sp new Circle Circle cp dynamic_cast Circle sp if cp cout cast successful The template argument for dynamic_cast is the type you want the function to produce and this is the return value for the function. The function argument is what you are trying to cast from. .

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
14    103    4    06-05-2024
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.