<P>以上回答的多态性的C++例子是:</P>
<pre><code>class Animal {
public:
Animal(const std::string& name) : name_(name) {}
virtual ~Animal() {}
virtual std::string talk() = 0;
std::string name_;
};
class Dog : public Animal {
public:
virtual std::string talk() { return "woof!"; }
};
class Cat : public Animal {
public:
virtual std::string talk() { return "meow!"; }
};
void main() {
Cat c("Miffy");
Dog d("Spot");
// This shows typical inheritance and basic polymorphism, as the objects are typed by definition and cannot change types at runtime.
printf("%s says %s\n", c.name_.c_str(), c.talk().c_str());
printf("%s says %s\n", d.name_.c_str(), d.talk().c_str());
Animal* c2 = new Cat("Miffy"); // polymorph this animal pointer into a cat!
Animal* d2 = new Dog("Spot"); // or a dog!
// This shows full polymorphism as the types are only known at runtime,
// and the execution of the "talk" function has to be determined by
// the runtime type, not by the type definition, and can actually change
// depending on runtime factors (user choice, for example).
printf("%s says %s\n", c2->name_.c_str(), c2->talk().c_str());
printf("%s says %s\n", d2->name_.c_str(), d2->talk().c_str());
// This will not compile as Animal cannot be instanced with an undefined function
Animal c;
Animal* c = new Animal("amby");
// This is fine, however
Animal* a; // hasn't been polymorphed yet, so okay.
}
</code></pre>