核心内容摘要
17c.5c-起草的关键步骤与要点:释放你的创意潜能,让灵感落地成金
在C中类型转换是将一个类型的值转换为另一个类型的操作分为隐式类型转换编译器自动完成和显式类型转换程序员主动指定两类。
隐式类型转换自动转换编译器在特定场景下自动触发的转换无需程序员干预通常发生在“类型兼容且安全”的场景中。
基础数据类型的隐式转换小范围→大范围当“小类型”赋值给“大类型”时编译器自动转换无数据丢失#includeiostreamusingnamespacestd;intmain(){//
char → int小整数类型→大整数类型charca;// a的ASCII值是97intic;// 隐式转换c的97自动转为int类型couti iendl;// 输出97//
int → double整数→浮点数intnum10;doublednum;// 隐式转换10自动转为
1
0coutd dendl;// 输出10//
表达式中的隐式转换混合类型运算inta5;doubleb
5;doubleresab;// aint隐式转为double结果为
5coutres resendl;// 输出
5return0;}
类的隐式转换单参数构造函数/类型转换运算符单参数构造函数允许用该参数类型的值“隐式构造”类对象类型转换运算符允许类对象“隐式转换”为其他类型。
#includeiostreamusingnamespacestd;classMyInt{private:int_val;public:// 单参数构造函数允许int→MyInt的隐式转换MyInt(intval):_val(val){}// 类型转换运算符允许MyInt→int的隐式转换operatorint()const{return_val;}voidshow()const{coutMyInt: _valendl;}};intmain(){//
int → MyInt单参数构造函数的隐式转换MyInt mi100;// 等价于 MyInt mi(
隐式转换mi.show();// 输出MyInt: 100//
MyInt → int类型转换运算符的隐式转换intnummi;// 隐式转换为intcoutnum numendl;// 输出100return0;}
显式类型转换强制转换程序员通过转换操作符主动指定的转换用于“编译器不会自动转换”的场景可能存在风险。
C提供4种显式转换 static_cast 、 dynamic_cast 、 const_cast 、 reinterpret_cast 。
static_cast 静态类型转换编译期检查用于相关类型的转换如基本类型、类的向上/向下转型编译期检查合法性但不保证运行时安全。
#includeiostreamusingnamespacestd;intmain(){//
基本类型转换大→小可能丢失数据doubled
14;intistatic_castint(d);// 显式转换
14→3couti iendl;// 输出3//
类的向上转型子类→父类安全classBase{};classDerived:publicBase{};Derived*d_ptrnewDerived();Base*b_ptrstatic_castBase*(d_ptr);// 向上转型安全//
类的向下转型父类→子类不安全编译期不检查Base*bnewBase();Derived*d2static_castDerived*(b);// 编译通过但运行时可能出错deleted_ptr;deleteb;return0;}
dynamic_cast 动态类型转换运行期检查仅用于类的指针/引用主要用于向下转型运行期检查类型兼容性失败时返回 nullptr 指针或抛出异常引用。
#includeiostreamusingnamespacestd;classBase{public:virtualvoidshow()const{coutBaseendl;}// 虚函数支持多态};classDerived:publicBase{public:voidshow()constoverride{coutDerivedendl;}};intmain(){Base*b1newDerived();// 父类指针指向子类对象Base*b2newBase();// 父类指针指向父类对象//
安全的向下转型b1指向子类Derived*d1dynamic_castDerived*(b
;if(d
{d1-show();// 输出Derived}//
不安全的向下转型b2指向父类Derived*d2dynamic_castDerived*(b
;if(!d
{coutd2 is nullptrendl;// 输出d2 is nullptr}deleteb1;deleteb2;return0;}
const_cast 常量性转换用于移除/添加 const 属性仅能用于指针/引用不能用于普通变量。
#includeiostreamusingnamespacestd;intmain(){constintnum10;// 移除const仅当原变量不是const时安全int*pconst_castint*(num);*p20;// 未定义行为原num是const修改会导致错误coutnum numendl;// 可能输出10编译器优化// 安全场景原变量不是const指针被const修饰intval5;constint*cpval;int*npconst_castint*(cp);*np15;coutval valendl;// 输出15return0;}
reinterpret_cast 重新解释转换用于不相关类型的转换如指针→整数、不同类型指针互转是最“暴力”的转换仅重新解释二进制不做类型检查风险极高。
#includeiostreamusingnamespacestd;intmain(){//