请设计4个类,“上帝”,“动物”,“狗”,“牛”,请简要写出类定义和实现代码,如有必要,可以引入辅助类。
1、全世界只有一个“上帝”。
2、只有“上帝”才能创造“动物”,“上帝”根据“动物”的名字创造“动物”。
3、所有的“动物”都会跑。
4、“狗”会吠。
5、“牛”会吃。
#include <iostream> #include <string> using namespace std; class Animal { public: void run() { cout << "runing." << endl; } virtual void DoSomething() { cout << "do something." << endl; } virtual ~Animal() { } }; class Dog:public Animal { public: void DoSomething() { cout << "dog bark." << endl; } }; class Cow:public Animal { public: void DoSomething() { cout << "cow eat." << endl; } }; class God { public: static God* CreatInstance(); Animal* CreateAnimal(string animalName) { if (animalName == "Dog") { pAnimal = new Dog(); } else if (animalName == "Cow") { pAnimal = new Cow(); } else { pAnimal = new Animal(); } return pAnimal; } ~God() { delete instance; delete pAnimal; } private: static God* instance; Animal* pAnimal; string animaName; God() : animaName("") , pAnimal(NULL) { } }; God* God::instance = NULL; God* God::CreatInstance() { if (instance == NULL) { instance = new God(); } return instance; } int _tmain(int argc, _TCHAR* argv[]) { God * pGod = God::CreatInstance(); // There is only one god Animal* pAnimal = NULL; pAnimal = pGod->CreateAnimal("Dog"); // God Creat Dog. pAnimal->run(); pAnimal->DoSomething(); pAnimal = pGod->CreateAnimal("Cow"); // God Creat Cow. pAnimal->run(); pAnimal->DoSomething(); int pause = 0; cin >> pause; return 0; }