#include <iostream>
#include <string>
using namespace std;
class Animal {
public:
Animal(const string& name) : name(name) {}
virtual string talk() = 0;
const string name;
};
class Cat : public Animal {
public:
Cat(const string& name) : Animal(name) {}
virtual string talk() { return "Meow!"; }
};
class Dog : public Animal {
public:
Dog(const string& name) : Animal(name) {}
virtual string talk() { return "Woof! Woof!"; }
};
// prints the following:
//
// Missy: Meow!
// Mr. Mistoffelees: Meow!
// Lassie: Woof! Woof!!
//
int main() {
Animal* animals[] = {
new Cat("Missy"),
new Cat("Mr. Mistoffelees"),
new Dog("Lassie")
};
for (int i = 0; i < 3; ++i) {
cout << animals[i]->name << ": " << animals[i]->talk() << endl;
delete animals[i];
}
return 0;
}
异质指针数组的例子
最新推荐文章于 2020-10-06 08:59:27 发布