cpp拾遗——类型转换
1. c和c++的类型转换
c只有编译时类型转换,包括隐式类型转换和显示类型转换。
cpp有编译时类型转换,和运行时类型转换,和const类型转换,
static_cast 编译时类型转换,效果相当于c的隐式转换
reinterpret_cast 编译时类型转换,效果相当于c的显示类型转换
dynamic_cast 运行时类型转换,父子类之间多态转换
const_cast const类型转换
格式:
type b = static_cast
2. static_cast reinterpret_cast
int a, *pi;
char c;
c = static_cast<char>(a);
pi = reinterpret_cast<int *>(a);
3. dynamic_cast
多态间转换,如果不能转换,则返回NULL,可用于判断父类指针指向的是哪个子类。
class animal_t {
public:
virtual void walk() = 0;
};
class dog_t : public animal_t {
public:
void walk() {
cout << "dog walk" << endl;
}
void house_keeping() {
cout << "wang wang" << endl;
}
};
class cat_t : public animal_t {
public:
void walk() {
cout << "cat walk" << endl;
}
void sell_cute() {
cout << "cute cute" << endl;
}
};
void test(animal_t *a)
{
a->walk();
cat_t *cat = dynamic_cast<cat_t *>(a);
if (cat != NULL) {
cat->sell_cute();
}
dog_t *dog = dynamic_cast<dog_t *>(a);
if (dog != NULL) {
dog->house_keeping();
}
}
int main()
{
cat_t cat;
test(&cat);
dog_t dog;
test(&dog);
return 0;
}
4. const_cast
常用于去除const只读属性,但程序员需要保证内存可写。
const char *str = "aaaaa";
const char str2[] = "aaaaa";
char *p;
p = const_cast<char *>(str);
p[0] = 1; // 错误
p = const_cast<char *>(str2);
p[0] = 1;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?