In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how to use dynamic_cast and static_cast in C++". The editor shows you the operation process through an actual case. The method of operation is simple, fast and practical. I hope this article "how to use dynamic_cast and static_cast in C++" can help you solve the problem.
1. Static_cast
1.1 static_cast syntax
Static_cast
< new_type >(expression)
Note: new_type is the target data type, and expression is the original data type variable or expression.
C style:
Double scores = 96.5 witint n = (int) scores
The new style of C++ is written as follows:
Double scores = 96.5 int n = static_cast (scores); 1.2Why should there be static_cast, etc.
Implicit type conversion is safe, explicit type conversion is risky, and C language adds mandatory type conversion syntax to emphasize risks and make programmers aware of what they are doing.
However, this way of emphasizing risk is still relatively extensive and the granularity is relatively large, and it does not show what the risk is and how the degree of risk is.
In order to refine the potential risks, facilitate problem traceability, and standardize the writing format, C++ classifies type conversions and adds four new keywords to support them:
Keyword indicates that static_cast is used for benign conversion, which generally does not cause accidents, and the risk is very low. Const_cast is used for conversion between const and non-const, volatile and non-volatile. Reinterpret_cast 's highly dangerous conversion, which is merely a reinterpretation of binary bits, does not adjust the data with existing conversion rules, but enables the most flexible C++ type conversion. Dynamic_cast uses RTTI for type-safe downward transformation (Downcasting). 1.2 the role of static_cast
Static_cast is equivalent to the traditional C language cast, the operator converts expression to new_type type, used to force implicit conversions such as non-const objects to const objects, compile-time checking, for non-polymorphic conversion, can convert pointers and others, but there is no run-time type checking to ensure the security of the conversion. It has the following main uses:
Low-risk usage:
Original automatic type conversion, such as short to int, int to double, const to non-const, upward transformation, etc.
Conversion between void pointer and specific type pointer, such as void * to int *, char * to void *, etc.
Conversion between classes with conversion constructors or type conversion functions and other types, such as double to Complex (call conversion constructor) and Complex to double (call type conversion function).
It is important to note that static_cast cannot be used for conversions between extraneous types because these conversions are risky, such as:
Conversion between two specific types of pointers, such as int * to double *, Student * to int *, and so on. Different types of data are stored in different formats and lengths. After pointing to data of type B with a pointer of type A, the data will be processed in the same way as type A: if it is a read operation, you may get a pile of meaningless values; if it is a write operation, it may destroy the data of type B, and you will get a pile of meaningless values when you read the data in type B again.
Conversion between int and pointer. Assigning a specific address to a pointer variable is very dangerous because the memory at that address may not be allocated, or it may not have read and write access, and it happens that the available memory is a small probability event instead.
1.3 static_cast usage # include # include using namespace std;class Complex {public: Complex (double real = 0, double imag = 0): m_real (real), m_imag (imag) {} public: operator double () const {return mrealizations;} / / Type conversion function private: double mrealms; double mrealms;}; int main () {/ / the following is the correct usage int m = 100 Complex c (12.5,23.8); long n = static_cast (m); / / wide conversion, no information loss char ch = static_cast (m); / / narrow conversion, may lose information int * p1 = static_cast (malloc (10 * sizeof (int); / / convert void pointer to specific type pointer void * p2 = static_cast (p1) / / convert a specific type pointer to a void pointer double real= static_cast (c); / call the type conversion function / / the following usage is the wrong float * p3 = static_cast (p1); / / cannot convert p3 = static_cast (0X2DF9) between two specific types of pointers; / / cannot convert an integer to a pointer type return 0 } 2. Dynamic_cast2.1 dynamic_cast syntax dynamic_cast (expression)
NewType and expression must be pointer or reference types at the same time. In other words, dynamic_cast can only convert pointer types and reference types, not other types (int, double, arrays, classes, structs, and so on).
For pointers, NULL; is returned if the conversion fails for references, and a std::bad_cast exception is thrown if the conversion fails.
2.2 dynamic_cast usage
Dynamic_cast is used for type conversion between inheritance hierarchies of classes, allowing both upward and downward transitions (Upcasting) as well as Downcasting. The upward transition is unconditional and will not be tested, so it can be successful; the premise of the downward transition must be safe, and only part of it can be successful with the help of RTTI testing.
Dynamic_cast is relative to static_cast. Dynamic_cast means "dynamic transformation" and static_cast means "static transformation". Dynamic_cast uses RTTI for type conversion while the program is running, which requires that the base class must contain virtual functions; static_cast completes type conversion during compilation and can find errors in a more timely manner.
2.3 dynamic_cast instance
2.3.1 upward transition (Upcasting)
In an upward transition, as long as there is an inheritance relationship between the two types to be converted, and the base class contains virtual functions (this information can be determined during compilation), the conversion will be successful. Because the upward transition is always safe, dynamic_cast does not do any run-time checks, so there is no difference between dynamic_cast and static_cast at this time.
"do not perform run-time detection during upward transition" improves efficiency, but it also leaves security risks, see the following code:
# include # include using namespace std;class Base {public: Base (int a = 0): virtual void func (a) {} int get_a () const {return massia;} virtual void func () const {} protected: int massia;}; class Derived: public Base {public: Derived (int a = 0, int b = 0): Base (a), mubb (b) {} int get_b () const {return massib } private: int massib;}; int main () {/ / case ① Derived * pd1 = new Derived (35,78); Base * pb1 = dynamic_cast (pd1); cout
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.