diff --git a/day7/homework/h7.cpp b/day7/homework/h7.cpp index eb0c8db..dbc7916 100644 --- a/day7/homework/h7.cpp +++ b/day7/homework/h7.cpp @@ -44,6 +44,7 @@ catch (int e) ********************************************************************/ #include +#include using namespace std; @@ -74,51 +75,60 @@ public: int main() { Animal *ap = new Animal(); // 创建一个 Animal 类型的指针 + try { Cat *cp = dynamic_cast(ap); // 将其转换为 Cat 类型的指针 - cp->meow(); + if (cp) + cp->meow(); + else + throw 1; } - catch (int e) + catch (int &e) { - cout << "dynamic_cast 将 Animal 转换为 Cat 失败" << endl - << e << endl; + cout << "dynamic_cast 将 Animal 转换为 Cat 失败" << endl; } Animal *ap2 = new Animal(); // 创建一个 Animal 类型的指针 try { Dog *dp = dynamic_cast(ap2); // 将其转换为 Dog 类型的指针 - dp->bark(); + if (dp) + dp->bark(); + else + throw 1; } - catch (int e) + catch (int &e) { - cout << "dynamic_cast 将 Animal 转换为 Dog 失败" << endl - << e << endl; + cout << "dynamic_cast 将 Animal 转换为 Dog 失败" << endl; } Cat *cp2 = new Cat(); // 创建一个 Cat 类型的指针 try { Animal *ap3 = dynamic_cast(cp2); // 将其转换为 Animal 类型的指针 - cout << "dynamic_cast 将 Cat 转换为 Animal 成功" << endl; + if (ap3) + cout << "dynamic_cast 将 Cat 转换为 Animal 成功" << endl; + else + throw 1; } - catch (int e) + catch (int &e) { - cout << "dynamic_cast 将 Cat 转换为 Animal 失败" << endl - << e << endl; + cout << "dynamic_cast 将 Cat 转换为 Animal 失败" << endl; } Dog *dp2 = new Dog(); // 创建一个 Dog 类型的指针 try { Animal *ap4 = dynamic_cast(dp2); // 将其转换为 Animal 类型的指针 - cout << "dynamic_cast 将 Dog 转换为 Animal 成功" << endl; + if (ap4) + cout << "dynamic_cast 将 Dog 转换为 Animal 成功" << endl; + else + throw 1; } - catch (int e) + catch (int &e) { - cout << "dynamic_cast 将 Dog 转换为 Animal 失败" << endl - << e << endl; + cout << "dynamic_cast 将 Dog 转换为 Animal 失败" << endl; } return 0;