hour18_3.cpp
来自「《24学时精通c++》的随书源码的下半部分。欢迎下载学习。」· C++ 代码 · 共 74 行
CPP
74 行
// Listing 18.2 - dynamic cast
#include <iostream>
using std::cout; // this file uses std::cout
class Mammal
{
public:
Mammal():itsAge(1) { cout << "Mammal constructor...\n"; }
virtual ~Mammal() { cout << "Mammal destructor...\n"; }
virtual void Speak() const { cout << "Mammal speak!\n"; }
protected:
int itsAge;
};
class Cat: public Mammal
{
public:
Cat() { cout << "Cat constructor...\n"; }
~Cat() { cout << "Cat destructor...\n"; }
void Speak()const { cout << "Meow\n"; }
void Purr() const { cout << "rrrrrrrrrrr\n"; }
};
class Dog: public Mammal
{
public:
Dog() { cout << "Dog Constructor...\n"; }
~Dog() { cout << "Dog destructor...\n"; }
void Speak()const { cout << "Woof!\n"; }
};
int main()
{
const int NumberMammals = 3;
Mammal* Zoo[NumberMammals];
Mammal* pMammal;
int choice,i;
for (i=0; i<NumberMammals; i++)
{
cout << "(1)Dog (2)Cat: ";
std::cin >> choice;
if (choice == 1)
pMammal = new Dog;
else
pMammal = new Cat;
Zoo[i] = pMammal;
}
cout << "\n";
for (i=0; i<NumberMammals; i++)
{
Zoo[i]->Speak();
Cat *pRealCat = dynamic_cast<Cat *> (Zoo[i]);
// if (pRealCat)
pRealCat->Purr();
// else
// cout << "Uh oh, not a cat!\n";
// You should get a runtime error when you try to get a dog to Purr
// You can't dynamicaly cast the wrong object type (dog to cat)
// The if test (now commented out) would catch the cast failure and
// Warn you that you did not have a cat...
delete Zoo[i];
cout << "\n";
}
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?