3, each animal derived class has a "first name" data member, this common member can be fully provided by the base class to transform the above program, the data member as an abstract class animal data members are used by the derived classes.
Code:
#include <iostream> #include <cstring> using namespace std;
Class Animal {protected:string name; Public:animal (string N): Name (n) {} virtual void cry () = 0;}; Class Mouse:public Animal {Private:char sex; Public:mouse (string N,char s): Animal (n), sex (s) {} virtual Voi
D Cry () {cout<< "I call" <<name<< ", is a";
if (sex== ' m ') cout<< "male";
else cout<< "female"; cout<< "The mouse, My cry is: Squeak Squeak."
"<<endl;
}
}; Class Cat:public Animal {Public:cat (string n): Animal (n) {} virtual void Cry () {cout<< "My name" < ;<name<< ", is a cat, my Cry is: Meow meow meow.
"<<endl;
}
}; Class Dog:public Animal {Public:dog (string n): Animal (n) {} virtual void Cry () {cout<< "My name" < ;<name<< ", is a dog, my cry is: Wang Bark.
"<<endl;
}
}; Class Giraffe:public Animal {Private:char sex; Public:giraffe (string N,char s): Animal (n), sex (s) {} virtual
void Cry () {cout<< "My name is" <<name<< ", is one";
if (sex== ' m ') cout<< "male";
else cout<< "female"; cout<< "Giraffes, my neck is too long to make a sound."
"<<endl;
}
};
int main () {Animal *p;
Mouse M1 ("Jerry", ' m ');
p=&m1;
P->cry ();
Mouse m2 ("Jemmy", ' f ');
p=&m2;
P->cry ();
Cat C1 ("Tom");
p=&c1;
P->cry ();
Dog D1 ("Droopy");
p=&d1;
P->cry ();
Giraffe G1 ("Gill", ' m ');
p=&g1;
P->cry ();
return 0;
}
Run Result: