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

126 lines
3.1 KiB
C++
Raw 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>
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 类型的指针
try
{
Cat *cp = dynamic_cast<Cat *>(ap); // 将其转换为 Cat 类型的指针
cp->meow();
}
catch (int e)
{
cout << "dynamic_cast 将 Animal 转换为 Cat 失败" << endl
<< e << endl;
}
Animal *ap2 = new Animal(); // 创建一个 Animal 类型的指针
try
{
Dog *dp = dynamic_cast<Dog *>(ap2); // 将其转换为 Dog 类型的指针
dp->bark();
}
catch (int e)
{
cout << "dynamic_cast 将 Animal 转换为 Dog 失败" << endl
<< e << endl;
}
Cat *cp2 = new Cat(); // 创建一个 Cat 类型的指针
try
{
Animal *ap3 = dynamic_cast<Animal *>(cp2); // 将其转换为 Animal 类型的指针
cout << "dynamic_cast 将 Cat 转换为 Animal 成功" << endl;
}
catch (int e)
{
cout << "dynamic_cast 将 Cat 转换为 Animal 失败" << endl
<< e << endl;
}
Dog *dp2 = new Dog(); // 创建一个 Dog 类型的指针
try
{
Animal *ap4 = dynamic_cast<Animal *>(dp2); // 将其转换为 Animal 类型的指针
cout << "dynamic_cast 将 Dog 转换为 Animal 成功" << endl;
}
catch (int e)
{
cout << "dynamic_cast 将 Dog 转换为 Animal 失败" << endl
<< e << endl;
}
return 0;
}