- /*定义一个基类 Animal,其中有一个虛函数perform(),用于在子类中实现不同动物的表演行为。*/
- #include
- using namespace std;
- class Animal //封装Animal类(基类)
- {
- private:
- string person;
- public:
- Animal() {}
- Animal(string person):person(person){}
- virtual void perform()
- {
- cout << person <<"正在讲解:" << endl;
-
- }
- };
-
- class T:public Animal//封装老虎类并继承Animal类(子类)
- {
- private:
- string name;
- string action;
- public:
- T() {}
- T(string name,string action):name(name),action(action)
- {}
- void perform()
- {
- cout << name << "正在表演 " << action << endl;
- }
- };
-
- class M:public Animal //封装猴子类并继承Animal类(子类)
- {
- private:
- string name;
- string action;
- public:
- M() {}
- M(string name,string action):name(name),action(action)
- {}
- void perform()
- {
- cout << name << "正在表演 " << action << endl;
- }
- };
-
- int main()
- {
- Animal a("讲解员");
- T b("老虎","跑");
- M c("猴子","爬树");
- Animal *p;
- p = &a;
- p->perform();
-
- p = &b;
- p->perform();
-
- p = &c;
- p->perform();
-
- return 0;
- }

