C++(四)类型强转
新类型的强制转换可以提供更好的控制强制转换过程,允许控制各种不同种类的强
制转换。C++提供了四种转化 static_cast,reinterpret_cast,dynamic_cast
和 const_cast 以满足不同需求,C++风格的强制转换好处是,它们能更清晰的表明
它们要干什么。
C 语言转换风格,在 C++中依然适用。
static_cast
| 语法格式 | static_cast(expression) |
|---|---|
| 适用场景 | static_cast 是 C++ 中的一种类型转换操作符,用于在相关类型之间进行显式转换。它提供了比 C 风格的类型转换更严格的类型检查,并且在许多情况下比 reinterpret_cast 更安全。 |
1. 基本数据类型之间的转换
static_cast 可以用于基本数据类型之间的转换,例如将 int 转换为 float,或者将 double 转换为 int:
int i = 42;
float f = static_cast<float>(i); // 将 int 转换为 float
double d = 3.14;
int j = static_cast<int>(d); // 将 double 转换为 int
CopyInsert
2. 指针类型之间的转换
在指针类型之间进行转换时,static_cast 可以用于在相关类型之间进行转换,例如在基类指针和派生类指针之间进行转换:
class Base {
public:
virtual void print() {
std::cout << "Base" << std::endl;
}
};
class Derived : public Base {
public:
void print() override {
std::cout << "Derived" << std::endl;
}
};
Base* basePtr = new Derived();
Derived* derivedPtr = static_cast<Derived*>(basePtr); // 将基类指针转换为派生类指针
derivedPtr->print(); // 输出 "Derived"
CopyInsert
3. 枚举类型和整数类型之间的转换
static_cast 可以用于枚举类型和整数类型之间的转换:
enum Color { RED, GREEN, BLUE };
Color c = RED;
int i = static_cast<int>(c); // 将枚举类型转换为整数类型
int j = 1;
Color c2 = static_cast<Color>(j); // 将整数类型转换为枚举类型
CopyInsert
4. 空指针类型的转换
static_cast 可以用于将 void* 指针转换为具体类型的指针:
void* voidPtr = malloc(sizeof(int));
int* intPtr = static_cast<int*>(voidPtr); // 将 void* 指针转换为 int* 指针
*intPtr = 42;
CopyInsert
5. 移除 const 限定符
虽然 static_cast 不能直接移除 const 限定符,但可以通过 const_cast 移除 const 后,再使用 static_cast 进行转换:
const int* constPtr = new int(42);
int* nonConstPtr = const_cast<int*>(constPtr); // 移除 const 限定符
int value = *nonC
C++类型转换详解

最低0.47元/天 解锁文章
1132

被折叠的 条评论
为什么被折叠?



