From 166515cf82e7c53891dfc8ee170fd53ff37419d2 Mon Sep 17 00:00:00 2001 From: flykhan Date: Thu, 3 Aug 2023 09:30:34 +0800 Subject: [PATCH] =?UTF-8?q?day7:=20homework=20=E4=BF=AE=E6=94=B9=E7=AC=AC7?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day7/homework/h7.cpp | 42 ++++++++++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 16 deletions(-) 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;