📅  最后修改于: 2023-12-03 15:14:06.647000             🧑  作者: Mango
C++ provides several types of casts, also called type conversions, which allow a value of one data type to be converted to another data type. The process of converting a value from one data type to another is known as casting.
Casting can be used for various purposes, such as:
The syntax for casting in C++ is as follows:
new_type(expression)
Here, new_type
is the target data type, and expression
is the value to be cast.
There are four types of casting available in C++:
Static Cast: This is the most commonly used type of cast in C++. It is used to convert a value from one data type to another data type. It checks if the casting is valid during compile time.
new_type = static_cast<new_type>(expression);
Dynamic Cast: This is used for casting a pointer or reference to a base class to a derived class (downcast). It checks if the casting is valid during runtime.
new_type = dynamic_cast<new_type>(expression);
Const Cast: This is used to remove the const
or volatile
qualifier from a variable. It can be used to cast a non-const variable to a const variable, but not vice versa.
new_type = const_cast<new_type>(expression);
Reinterpret Cast: This is used to convert a pointer to any other pointer type, even if the source pointer and destination pointer are of different types. It should be used with caution as it may lead to undefined behavior.
new_type = reinterpret_cast<new_type>(expression);
// Converting an int to double using static_cast
int myInt = 10;
double myDouble = static_cast<double>(myInt);
// Casting a base class pointer to a derived class pointer using dynamic_cast
class BaseClass { /* ... */ };
class DerivedClass : public BaseClass { /* ... */ };
BaseClass* basePtr = new DerivedClass();
DerivedClass* derivedPtr = dynamic_cast<DerivedClass*>(basePtr);
// Removing const from a variable using const_cast
const int myConst = 10;
int myNonConst = const_cast<int>(myConst);
// Casting an int pointer to a char pointer using reinterpret_cast
int* myIntPtr = new int[10];
char* myCharPtr = reinterpret_cast<char*>(myIntPtr);