// ============================================================================ // p1c06_01 — 6.1 静态转换(static_cast) // 来源:川大 C++/LinuxC wiki「02.Qt方向」 // 说明:本文件由 gen_part1.py 合并页面中的教学片段而成。每个片段用 // // --- 原文片段 [pageId:blockIdx] --- 标注出处。 // 已做最小修正(笔误/平台移植),详见 docs/ERRATA.md。 // ============================================================================ #include using namespace std; // --- 原文片段 [58954473:0] 6.1 静态转换(static_cast) --- class Animal{}; class Dog : public Animal{}; class Other{}; //基础数据类型转换 void test01(){ char a = 'a'; double b = static_cast(a); } //继承关系指针互相转换 void test02(){ //继承关系指针转换 Animal* animal01 = NULL; Dog* dog01 = NULL; //子类指针转成父类指针,安全 Animal* animal02 = static_cast(dog01); //父类指针转成子类指针,不安全 Dog* dog02 = static_cast(animal01); } //继承关系引用相互转换 void test03(){ Animal ani_ref; Dog dog_ref; //继承关系指针转换 Animal& animal01 = ani_ref; Dog& dog01 = dog_ref; //子类指针转成父类指针,安全 Animal& animal02 = static_cast(dog01); //父类指针转成子类指针,不安全 Dog& dog02 = static_cast(animal01); } //无继承关系指针转换 void test04(){ Animal* animal01 = NULL; Other* other01 = NULL; //转换失败 //Animal* animal02 = static_cast(other01); } // --- main --- int main() { test01(); test02(); test03(); test04(); return 0; }