diff --git a/day7/homework/h7.cpp b/day7/homework/h7.cpp index dbc7916..31fb929 100644 --- a/day7/homework/h7.cpp +++ b/day7/homework/h7.cpp @@ -131,5 +131,10 @@ int main() cout << "dynamic_cast 将 Dog 转换为 Animal 失败" << endl; } + delete ap; + delete ap2; + delete cp2; + delete dp2; + return 0; } diff --git a/day7/homework/h7_2.cpp b/day7/homework/h7_2.cpp new file mode 100644 index 0000000..395454c --- /dev/null +++ b/day7/homework/h7_2.cpp @@ -0,0 +1,105 @@ +#include +#include + +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; + } +}; + +int main() +{ + // 任务1:将Animal类型指针转换为Cat类型指针 + Animal *animal1 = new Cat(); + try + { + Cat *cat = dynamic_cast(animal1); + if (cat) + { + cat->meow(); + } + else + { + throw 1; + } + } + catch (int e) + { + std::cout << "转换失败:无法将Animal类型转换为Cat类型。" << std::endl; + } + + // 任务2:将Animal类型指针转换为Dog类型指针 + Animal *animal2 = new Dog(); + try + { + Dog *dog = dynamic_cast(animal2); + if (dog) + { + dog->bark(); + } + else + { + throw 2; + } + } + catch (int e) + { + std::cout << "转换失败:无法将Animal类型转换为Dog类型。" << std::endl; + } + + // 任务3:将Cat类型指针转换为Animal类型指针 + Cat *cat2 = new Cat(); + try + { + Animal *animal3 = dynamic_cast(cat2); + if (animal3) + { + std::cout << "转换成功:Cat类型成功转换为Animal类型。" << std::endl; + } + } + catch (const std::bad_cast &e) + { + std::cout << "转换失败:" << e.what() << std::endl; + } + + // 任务4:将Dog类型指针转换为Animal类型指针 + Dog *dog2 = new Dog(); + try + { + Animal *animal4 = dynamic_cast(dog2); + if (animal4) + { + std::cout << "转换成功:Dog类型成功转换为Animal类型。" << std::endl; + } + } + catch (const std::bad_cast &e) + { + std::cout << "转换失败:" << e.what() << std::endl; + } + + // 释放内存 + delete animal1; + delete animal2; + delete cat2; + delete dog2; + + return 0; +}