声明一个哺乳动物类Mammal,再由此派生出狗类Dog和猫类Cat。 程序要求: (1)Mammal类中定义名为color和weight的数据成员,分别用来存储动物的颜色和体重;并在Mammal类中定义一个虚函数print,用于输出color和weight值。 (2)每个类中都定义一个名为count的静态数据成员,用来存储各类对象的总数; (3)每个类都有构造函数和析构函数,在构造函数中对color和weight进行初始化,以及执行count++语句,在析构函数中执行count--语句。在Dog和Cat类中输出各自的信息,输出信息要有所区别; (4)主函数中以一般方法定义各类若干个对象,用new创建几个对象指针,用delete删除对象指针。在不同的位置输出各类count的值。最后输出"Main function ends."。
时间: 2024-02-18 14:05:29 浏览: 64
好的,以下是代码实现:
```cpp
#include <iostream>
using namespace std;
// 哺乳动物类
class Mammal {
public:
Mammal(string c, double w) : color(c), weight(w) { count++; }
virtual ~Mammal() { count--; }
virtual void print() { cout << "Color: " << color << ", Weight: " << weight << endl; }
static int count;
protected:
string color;
double weight;
};
int Mammal::count = 0;
// 狗类
class Dog : public Mammal {
public:
Dog(string c, double w, string b) : Mammal(c, w), breed(b) { count++; }
~Dog() { count--; }
void print() { cout << "This is a dog. Breed: " << breed << ", "; Mammal::print(); }
static int count;
private:
string breed;
};
int Dog::count = 0;
// 猫类
class Cat : public Mammal {
public:
Cat(string c, double w, bool f) : Mammal(c, w), isFat(f) { count++; }
~Cat() { count--; }
void print() { cout << "This is a cat. Is fat: " << (isFat ? "yes" : "no") << ", "; Mammal::print(); }
static int count;
private:
bool isFat;
};
int Cat::count = 0;
int main() {
Mammal m1("brown", 30), m2("black", 50);
Dog* d1 = new Dog("white", 20, "Golden Retriever");
Dog* d2 = new Dog("black", 25, "Labrador");
Cat* c1 = new Cat("gray", 5, false);
Cat* c2 = new Cat("white", 3, true);
cout << "Mammal count: " << Mammal::count << endl;
cout << "Dog count: " << Dog::count << endl;
cout << "Cat count: " << Cat::count << endl;
m1.print();
m2.print();
d1->print();
d2->print();
c1->print();
c2->print();
delete d1;
delete d2;
delete c1;
delete c2;
cout << "Mammal count: " << Mammal::count << endl;
cout << "Dog count: " << Dog::count << endl;
cout << "Cat count: " << Cat::count << endl;
cout << "Main function ends." << endl;
return 0;
}
```
输出结果如下:
```
Mammal count: 6
Dog count: 2
Cat count: 2
Color: brown, Weight: 30
Color: black, Weight: 50
This is a dog. Breed: Golden Retriever, Color: white, Weight: 20
This is a dog. Breed: Labrador, Color: black, Weight: 25
This is a cat. Is fat: no, Color: gray, Weight: 5
This is a cat. Is fat: yes, Color: white, Weight: 3
Mammal count: 2
Dog count: 0
Cat count: 0
Main function ends.
```
可以看到,程序按照要求正确地输出了各个类的信息和对象数量,并正确地进行了内存管理。
阅读全文