day7: homework 修改第7题

This commit is contained in:
flykhan 2023-08-03 09:30:34 +08:00
parent 8c46e7a977
commit 166515cf82
1 changed files with 26 additions and 16 deletions

View File

@ -44,6 +44,7 @@ catch (int e)
********************************************************************/
#include <iostream>
#include <typeinfo>
using namespace std;
@ -74,51 +75,60 @@ public:
int main()
{
Animal *ap = new Animal(); // 创建一个 Animal 类型的指针
try
{
Cat *cp = dynamic_cast<Cat *>(ap); // 将其转换为 Cat 类型的指针
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<Dog *>(ap2); // 将其转换为 Dog 类型的指针
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<Animal *>(cp2); // 将其转换为 Animal 类型的指针
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<Animal *>(dp2); // 将其转换为 Animal 类型的指针
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;