6-2 polymorphism and virtual function
Nid=24#time "title=" C, C + +, go, Haskell, Lua, Pascal time limit1000ms Memory Limit 65536K java, Python2, Python3, Ruby, Perl Time limit2000ms Memory Limit 131072K "style=" padding:0px; margin:0px; Color:rgb (83,113,197); Text-decoration:none ">time limit:1000ms Memory limit:65536k have questions? Dot here ^_^
Description of the topic through the practice of this topic can grasp the concept of polymorphism and the definition of virtual function and usage requirements define a base class pet, which has a character pointer data member name and a virtual member function speak () is used to output pet calls.; derived classes dog and cat derive from base class pet.
They inherit from the base class and rewrite the Speak () function again. For the output of the call of the dog class and Cat class respectively (detailed output Content reference demo sample output). Requires the use of virtual function technology to write code, so that the program can output the following content. Input
No
Output
The output data together has 3 rows. This topic requires the output to be the same as in the demo sample.
Demo sample Input
Demo sample Output
How does a pet speak? I am a cat,my name is Tom My sound is miao!miao! I am a dog,my name is Snoppy My sound is wang!wang!
Hint Source
#include <iostream>using namespace Std;class pet{public: virtual void speak ()//define virtual function { cout< < "How does a pet speak?" <<endl;} ; Class Cat:public Pet{public: void Speak () { cout << "I am a cat,my name is Tom My sound is miao!miao!" <<endl;} ; Class Dog:public Pet{public: void Speak () { cout<< "I am a dog,my name is Snoppy My sound is Wang!wan g! " <<endl;} ; int main () { pet P, *t;//defines the pointer of the pet class object T Cat C; Dog D; t = &p;//t pointer p t->speak ();//Call p.speak function t = &c;//t pointer C t->speak ();//Call c.speak function t = &d;//t pointer D t->speak ();//Call d.speak function return 0;}
Sdut 6-2 polymorphism and virtual function