English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Type casting operators are special operators that convert one data type to another. Type casting operators are unary operators, and their precedence is the same as that of other unary operators.
Most of the C++ Compilers support most general type casting operators:
(type) expression
where type is the converted data type. The following lists C++ Other type casting operators supported:
const_cast<type> (expr): The const_cast operator is used to modify the const of the type / volatile attribute. In addition to const or volatile attributes, the target type must be the same as the source type. This type of conversion is mainly used to operate the const attribute of the object passed, and can add or remove const attributes.
dynamic_cast<type> (expr): dynamic_cast performs casting at runtime, verifying the validity of the conversion. If the conversion is not performed, the conversion fails, and the expression expr is deemed null. dynamic_cast performs dynamic casting when type must be a class pointer, class reference, or void*If type is a class pointer type, then expr must also be a pointer. If type is a reference, then expr must also be a reference.
reinterpret_cast<type> (expr): The reinterpret_cast operator changes a pointer to another type of pointer. It can convert a pointer to an integer, or an integer to a pointer.
static_cast<type> (expr): The static_cast operator performs non-dynamic casting, without runtime class checks to ensure the safety of the conversion. For example, it can be used to convert a base class pointer to a derived class pointer.
All the type casting operators mentioned above are used when working with classes and objects. Now, please see the following example to understand C++ How to use a simple type casting operator. Copy and paste the following C++ Program to test.cpp file, compile and run the program.
#include <iostream> using namespace std; int main() { double a = 21.09399; float b = 10.20; int c; c = (int) a; cout << "Line"1Line-(int) a's value is: " << c << endl; c = (int) b; cout << "Line"2Line-(int) b's value is: " << c << endl; return 0; }
When the above code is compiled and executed, it will produce the following results:
Line1Line-(int) b's value is:21 Line2Line-(int) b's value is:10