How do you use static_cast in C++?

In C++, static_cast is a type conversion operator used for performing static casts. It allows for type checking at compile time and can only be used for conversions between related types.

The basic syntax of static_cast is as follows:

static_cast<目标类型>(源表达式)

The target type is the type you want to convert the source expression to. The source expression can be any convertible type, such as pointers, references, basic data types, etc.

Here are some examples of usage:

  1. Conversion of primitive types:
int num = 10;
double num_double = static_cast<double>(num);
  1. Converting pointer types:
int* ptr = new int(10);
void* void_ptr = static_cast<void*>(ptr);
  1. Conversion of citation types:
int num = 10;
double& num_ref = static_cast<double&>(num);

It should be noted that static_cast cannot perform all types of conversions, as it has certain limitations. For example, it cannot be used to remove constantness or convert pointers to unrelated types. For these cases, other type casting operators such as const_cast, reinterpret_cast, etc., can be used.

bannerAds