学习日记|C++中static_cast和dynamic_cast


//两种类型转换用于处理类之间的转换,dynamic_cast只能在多态中的使用(有虚函数) /* 总结: 1 上行指针向下转 static不报错,编译通过,运行时不报错 dynamic,编译通过,运行时根据对象会报错2 子类指针向上转 符合继承关系,都成功 3 胡乱转 dynamic运行时报错,static编译不通过 */ namespace C7N2_Cast { //class base class base { public: virtual void vFunc() { cout << "base vFunc" << endl; cout << str << endl; } void print() { cout << str << endl; } base() { str = "base"; } private: string str; }; //class derive1 :public base class derive1 :public base { public: virtual void vFunc() { cout << "derive1 vFunc" << endl; cout << str << endl; } void print() { cout << str << endl; } derive1() { str = "derive1"; } private: string str; }; //class derive2 :public base class derive2 :public base { public: virtual void vFunc() { cout << "derive2 vFunc" << endl; cout << str << endl; } void print() { cout << str << endl; } derive2() { str = "derive2"; } private: string str; }; void test() { base b1, *pbb,*pbd; derive1 d1, *pdd, *pdb; pbb = &b1; pbd = &d1; pdd = &d1; //pdb = &b1; //error:子类指针不能指向父类对象//dynamic_cast //1.1 上行指针 向下转 //对象符合-->成功 if (dynamic_cast(pbd) == nullptr) { cout << "dynamic_cast(pbd)时失败" << endl; } //对象不符合-->失败 if (dynamic_cast(pbd) == nullptr) { cout << "dynamic_cast(pbd)时失败" << endl; //失败 } //1.2 子类指针向上转 //符合继承关系-->成功 if (dynamic_cast(pdd) == nullptr) { cout << "dynamic_cast(pdd)时失败" << endl; } //1.3 胡乱转 //不满足继承关系-->失败 if (dynamic_cast(pdd) == nullptr) { cout << "dynamic_cast(pdd)时失败" << endl; //失败 }//static_case //2.1 上行指针向下转 //对象符合-->成功 if (static_cast(pbd) == nullptr) { cout << "static_cast(pbd)时失败" << endl; } //对象不符合-->不报错 if (static_cast(pbd) == nullptr) { cout << "static_cast(pbd)时失败" << endl; } //2.2 子类指针 向上转 //符合继承关系-->成功 if (static_cast(pdd) == nullptr) { cout << "static_cast(pdd)时失败" << endl; } //不符合继承关系-->编译不通过 //if (static_cast(pdd) == nullptr) { //cout << "static_cast(pdd)时失败" << endl; //没有类型检查 //} //2.3 胡乱转 //编译都不通过 } }


    推荐阅读