题目:定义了一个基类Animal,它包含两个私有数据成员,一个是string成员,存储动作的名称(“Fido”),一个是整数成员weight,存储了动物的重量(单位是磅)。该基类还包含一个公共的虚拟成员函数who()和一个纯虚函数sound(),公共的虚拟成员函数who()返回一个string对象,该对象包含了Animal对象的名称和重量,纯虚函数sound()在派生类中应返回一个string对象,表示该动物发出的声音。把Animal类作为一个公共基类,派生至少三个类Sheep、Dog和Cow,在每个类中实现sound()函数。
定义一个类Zoo,它至多可以在一个数组中存储50种不同类型的动作(使用指针数组)。编写一个main()函数函数,创建给定数量的派生类对象的随机序列,在Zoo对象中存储这些对象(使用指针数组)。编写一个main()函数,创建给定数量的派生类对象的随机序列,在Zoo对象中存储这些对象的指针。使用Zoo对象的一个成员函数,输出Zoo中每个动物的信息,以及每个动物发出的声音。
参考答案:
Animal.h
// Animal.h
// Animal classes and class defining a zoo
#ifndef ANIMAL_H
#define ANIMAL_H
#include <string>
using std::string;
class Animal {
public:
Animal(string theName, int wt); // Constructor
virtual string who() const; // Return string containing name and weight
virtual string sound() = 0; // Display sound of an animal
private:
string name;
int weight;
};
class Sheep: public Animal {
public:
Sheep(string theName, int wt): Animal(theName, wt) {}
string who() const; // Return string containing name and weight
string sound(); // Display sound of a sheep
};
class Dog: public Animal {
public:
Dog(string theName, int wt): Animal(theName, wt) {}
string who() const; // Return string containing name and weight
string sound(); // Display sound of a dog
};
class Cow: public Animal {
public:
Cow(string theName, int wt): Animal(theName, wt) {}
string who() const; // Return string containing name and weight
string sound(); // Return sound of a cow
};
// The Zoo class shows how you can use an enumeration
// to get a constant as part of a class definition.
// This is used to specify the dimension of the array member.
class Zoo {
public:
Zoo(): number(0) {} // Default constructor for an empty zoo
Zoo(Animal** pNewAnimal, int count); // Constructor from an array of animals
bool addAnimal(Animal* pAnimal); // And an animal to the zoo
void showAnimals(); // Output the animals and the sound they make
private:
enum { maxAnimals = 50 }; // Defines maximum number of animals
Animal* pAnimals[maxAnimals]; // Stores addresses of the animals
int number; // Number of animals in the Zoo
};
#endif
Animal.cpp
// Animal.cpp
// Implementations of the Animal class and classes derived from Animal
#include "Animal.h"
#include <string>
#include <cstdlib>
#include <iostream>
using std::string;
using std::cout;
using std::endl;
// Constructor
Animal::Animal(string theName, int wt): name(theName), weight(wt) {}
// Return string decribing the animal
string Animal::who() const {
char wtstr[10];
return string("My name is ") + name + string(". My weight is ") + string(itoa(weight, wtstr, 10)) + string(" lbs.");
}
// Return string decribing the sheep
string Sheep::who() const {
return string("I'm a sheep. ") + Animal::who(); // Call base function for common data
}
// Make like a sheep
string Sheep::sound() {
return string("Baaaa!!");
}
// Return string decribing the dog
string Dog::who() const {
return string("I'm a dog. ") + Animal::who(); // Call base function for common data
}
// Make like a dog
string Dog::sound() {
return string("woof woof!!");
}
// Return string decribing the cow
string Cow::who() const {
return string("I'm a cow. ") + Animal::who(); // Call base function for common data
}
// Make like a cow
string Cow::sound() {
return string("Mooooo!!!");
}
// Constructor from an array of animals
Zoo::Zoo(Animal** pNewAnimals, int count) {
if (count > maxAnimals) {
cout << "\nMaximum animals allowed is " << maxAnimals
<< ". Only that number stored.";
count = maxAnimals;
}
for (int i=0; i<count; i++) {
pAnimals[i] = pNewAnimals[i];
}
number = count;
}
// Add an animal to the zoo
// Returns true if the animal is added successfully.
bool Zoo::addAnimal(Animal* pAnimal) {
if (number == maxAnimals) {
cout << "\nThe zoo is full. Animal not stored.";
return false;
}
pAnimals[number++] = pAnimal;
return true;
}
// Output the animals and the sound they make
void Zoo::showAnimals() {
for (int i=0; i<number; i++)
cout << endl << pAnimals[i]->who() << ' ' << pAnimals[i]->sound();
}
main.cpp
// main.cpp -- Exercising Zoo and Animal classes
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Animal.h"
using std::cout;
using std::endl;
using std::string;
// Function to generate a random integer 0 to count-1
int random(int count) {
return static_cast<int>((count*static_cast<long>(rand()))/(RAND_MAX+1L));
}
void main() {
srand((unsigned)time(0)); // Seed rand number generator
char* dogNames[] = { "Fido", "Rover", "Lassie", "Lambikins", "Poochy",
"Spit", "Gnasher", "Samuel", "Wellington", "Patch" };
char* sheepNames[] = { "Bozo", "Killer", "Tasty", "Woolly", "Chops",
"Blackie", "Whitey", "Eric", "Sean", "Shep" };
char* cowNames[] = { "Dolly", "Daisy", "Shakey", "Amy", "Dilly",
"Dizzy", "Eleanor", "Zippy", "Zappy", "Happy" };
int minDogWt = 1; // Minimum weight of a dog in pounds
int maxDogWt = 120; // Maximum weight of a dog in pounds
int minSheepWt = 80; // Minimum weight of sheep in pounds
int maxSheepWt = 150; // Maximum weight of sheep in pounds
int minCowWt = 800; // Minimum weight of cow in pounds
int maxCowWt = 1500; // Maximum weight of cow in pounds
Animal* pAnimals[20]; // Array to store pointers to animals
int numAnimals = sizeof pAnimals/sizeof(Animal*);
// Create random animals
for (int i=0; i<numAnimals; i++) {
switch(random(3)) {
case 0: // Create a sheep
pAnimals[i] = new Sheep(sheepNames[random(sizeof sheepNames/sizeof(char*))],
minSheepWt + random(maxSheepWt - minSheepWt + 1));
break;
case 1: // Create a dog
pAnimals[i] = new Dog(dogNames[random(sizeof dogNames/sizeof(char*))],
minSheepWt + random(maxDogWt - minDogWt + 1));
break;
case 2: // Create a cow
pAnimals[i] = new Cow(cowNames[random(sizeof cowNames/sizeof(char*))],
minCowWt + random(maxCowWt - minCowWt + 1));
break;
default:
cout << "\nInvalid animal type selection.";
break;
}
}
// Create a Zoo containing the animals
// You could also create an empty zoo and add animals one at a time
Zoo theZoo(pAnimals, numAnimals);
theZoo.showAnimals(); // Display the animals
// Release memory for the animals
// Note that the array was not created dynamically
// so we must not try to delete the array - just the individual elements
for (int j = 0; j < numAnimals; j++)
delete pAnimals[j];
cout << endl;
}