qfedu-cpp-level/day7/homework/h7.cpp

135 lines
3.2 KiB
C++
Raw Permalink Normal View History

2023-08-01 22:54:37 +08:00
/********************************************************************
Animal Cat Dog : class Animal
{
public:
virtual ~Animal() {}
};
class Cat : public Animal
{
public:
void meow()
{
std::cout << "Meow!" << std::endl;
}
};
class Dog : public Animal
{
public:
void bark()
{
std::cout << "Woof!" << std::endl;
}
};
1) main Animal 使 dynamic_cast Cat meow "Meow!"
2) main Animal 使 dynamic_cast Dog bark "Woof!"
3) main Cat 使 dynamic_cast Animal
4) main Dog 使 dynamic_cast Animal
try
{
}
catch (int e)
{
}
********************************************************************/
#include <iostream>
2023-08-03 09:30:34 +08:00
#include <typeinfo>
2023-08-01 22:54:37 +08:00
using namespace std;
class Animal
{
public:
virtual ~Animal() {}
};
class Cat : public Animal
{
public:
void meow()
{
cout << "Meow!" << endl;
}
};
class Dog : public Animal
{
public:
void bark()
{
cout << "Woof!" << endl;
}
};
int main()
{
Animal *ap = new Animal(); // 创建一个 Animal 类型的指针
2023-08-03 09:30:34 +08:00
2023-08-01 22:54:37 +08:00
try
{
Cat *cp = dynamic_cast<Cat *>(ap); // 将其转换为 Cat 类型的指针
2023-08-03 09:30:34 +08:00
if (cp)
cp->meow();
else
throw 1;
2023-08-01 22:54:37 +08:00
}
2023-08-03 09:30:34 +08:00
catch (int &e)
2023-08-01 22:54:37 +08:00
{
2023-08-03 09:30:34 +08:00
cout << "dynamic_cast 将 Animal 转换为 Cat 失败" << endl;
2023-08-01 22:54:37 +08:00
}
Animal *ap2 = new Animal(); // 创建一个 Animal 类型的指针
try
{
Dog *dp = dynamic_cast<Dog *>(ap2); // 将其转换为 Dog 类型的指针
2023-08-03 09:30:34 +08:00
if (dp)
dp->bark();
else
throw 1;
2023-08-01 22:54:37 +08:00
}
2023-08-14 17:20:39 +08:00
catch (...)
2023-08-01 22:54:37 +08:00
{
2023-08-03 09:30:34 +08:00
cout << "dynamic_cast 将 Animal 转换为 Dog 失败" << endl;
2023-08-01 22:54:37 +08:00
}
Cat *cp2 = new Cat(); // 创建一个 Cat 类型的指针
try
{
Animal *ap3 = dynamic_cast<Animal *>(cp2); // 将其转换为 Animal 类型的指针
2023-08-14 17:20:39 +08:00
cout << "dynamic_cast 将 Cat 转换为 Animal 成功" << endl;
2023-08-01 22:54:37 +08:00
}
2023-08-14 17:20:39 +08:00
catch (...)
2023-08-01 22:54:37 +08:00
{
2023-08-03 09:30:34 +08:00
cout << "dynamic_cast 将 Cat 转换为 Animal 失败" << endl;
2023-08-01 22:54:37 +08:00
}
Dog *dp2 = new Dog(); // 创建一个 Dog 类型的指针
try
{
Animal *ap4 = dynamic_cast<Animal *>(dp2); // 将其转换为 Animal 类型的指针
2023-08-14 17:20:39 +08:00
cout << "dynamic_cast 将 Dog 转换为 Animal 成功" << endl;
2023-08-01 22:54:37 +08:00
}
2023-08-14 17:20:39 +08:00
catch (...)
2023-08-01 22:54:37 +08:00
{
2023-08-03 09:30:34 +08:00
cout << "dynamic_cast 将 Dog 转换为 Animal 失败" << endl;
2023-08-01 22:54:37 +08:00
}
2023-08-03 09:42:28 +08:00
delete ap;
delete ap2;
delete cp2;
delete dp2;
2023-08-01 22:54:37 +08:00
return 0;
}