C++类型转换机制详解
C++类型转换机制详解
C++提供了四种显式类型转换运算符和一种隐式转换机制。理解不同转换方式的用途和限制对于编写安全的代码至关重要。
static_cast用于编译时已知的安全转换。
#include
void static_cast_example() {
int i = 10;
double d = static_cast(i);
std::cout << "int to double: " << d << "\n";
double pi = 3.14159;
int truncated = static_cast(pi);
std::cout << "double to int: " << truncated << "\n";
void* ptr = &i;
int* int_ptr = static_cast(ptr);
std::cout << "void* to int*: " << *int_ptr << "\n";
}
dynamic_cast用于运行时类型检查,只能用于多态类型。
class Base {
public:
virtual ~Base() = default;
virtual void identify() const {
std::cout << "Base\n";
}
};
class Derived : public Base {
public:
void identify() const override {
std::cout << "Derived\n";
}
void derived_method() {
std::cout << "Derived-specific method\n";
}
};
void dynamic_cast_example() {
Base* base_ptr = new Derived();
Derived* derived_ptr = dynamic_cast(base_ptr);
if (derived_ptr) {
derived_ptr->derived_method();
}
Base* base_only = new Base();
Derived* failed_cast = dynamic_cast(base_only);
if (!failed_cast) {
std::cout << "Cast failed as expected\n";
}
delete base_ptr;
delete base_only;
}
const_cast用于添加或移除const限定符。
void modify_through_const_cast(const int* ptr) {
int* mutable_ptr = const_cast(ptr);
*mutable_ptr = 100;
}
void const_cast_example() {
int x = 42;
const int* const_ptr = &x;
std::cout << "Before: " << x << "\n";
modify_through_const_cast(const_ptr);
std::cout << "After: " << x << "\n";
}
reinterpret_cast用于低级别的位模式重新解释。
void reinterpret_cast_example() {
int i = 65;
char* char_ptr = reinterpret_cast(&i);
std::cout << "First byte: " << *char_ptr << "\n";
long long address = reinterpret_cast(&i);
std::cout << "Address as number: " << std::hex << address << "\n";
}
隐式类型转换由编译器自动执行。
class Integer {
int value_;
public:
Integer(int v) : value_(v) {
std::cout << "Converting " << v << " to Integer\n";
}
operator int() const {
std::cout << "Converting Integer to int\n";
return value_;
}
};
void implicit_conversion() {
Integer i = 42;
int x = i;
std::cout << "Value: " << x << "\n";
}
explicit关键字防止隐式转换。
class ExplicitInteger {
int value_;
public:
explicit ExplicitInteger(int v) : value_(v) {}
explicit operator int() const {
return value_;
}
int value() const { return value_; }
};
void explicit_conversion() {
ExplicitInteger ei(42);
int x = static_cast(ei);
std::cout << "Value: " << x << "\n";
}
类型转换是C++中强大但危险的特性,应该谨慎使用,优先选择最安全的转换方式。
