6-1 polymorphism and virtual functions Time Limit: 1000 ms memory limit: 65536 k any questions? Click Here ^_^ Description
Through this exercise, you can understand the concept of polymorphism and the definition and usage of virtual functions.
Define a base class pet, which has a member function speak () used to output the pet call .; The derived classes dog and cat are derived from the base class pet. They inherited from the base class and rewritten the speak () function to output the sounds of the Dog class and cat class respectively. Virtual functions are required to write code so that the program can output the following content.
Input
None
Output
There are three rows of output data. The output content must be the same as that in the example.
Sample Input
Sample output
How does a pet speak ?miao!miao!wang!wang!
Prompt Source
# Include <iostream> using namespace STD; Class pet {public: Virtual void speak () // define the virtual function {cout <"how does a pet speak? "<Endl ;}}; class Cat: Public pet {public: void speak () {cout <" Miao! Miao! "<Endl ;}}; class Dog: Public pet {public: void speak () {cout <" Wang! Wang! "<Endl ;}; int main () {pet P, * t; // defines the pointer t cat c; DOG d; t = & P; // t pointer to p t-> speak (); // call p. speak function T = & C; // t pointer pointing to c t-> speak (); // calls C. speak function T = & D; // t pointer to d t-> speak (); // call D. speak function return 0 ;}
Sdut 6-1 polymorphism and virtual functions