编写程序:声明一个哺乳动物类Mammal,再 由此派生出狗类Dog和猫类Cat。 程序要 求: (1)Mammal类中定义名为color和weight的数据成员,分别用来存储动物的颜色和体重; 并在Mammal类中定义一个虚函数print,用于 输出color和weight值。 每个类中都定义一个名为count的静态数 据成员,用来存储各类对象的总数; (3)每个类都有构造函数和析构函数,在构 造函数中对color和weight进行初始化,以及 执行count++语句,在析构函数中执行count-- 语句。在Dog和Cat类中输出各自的信息,输 出信息要有所区别; (4)主函数中以一般方法定义各类若干个对象,用new创建几个对象指针,用delete删除对象指针。在不同的位置输出各类count的 值。最后输出"Main function ends."。
时间: 2024-02-24 09:58:30 浏览: 68
C++给出一个哺乳动物类,要求从此派生出一个狗类
3星 · 编辑精心推荐
以下是程序的代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Mammal {
protected:
string color;
double weight;
static int count;
public:
Mammal(string c, double w) : color(c), weight(w) { count++; }
virtual void print() {
cout << "Color: " << color << ", Weight: " << weight << endl;
}
virtual ~Mammal() { count--; }
static int getCount() { return count; }
};
int Mammal::count = 0;
class Dog : public Mammal {
public:
Dog(string c, double w) : Mammal(c, w) {}
void print() {
cout << "This is a dog. ";
Mammal::print();
}
};
class Cat : public Mammal {
public:
Cat(string c, double w) : Mammal(c, w) {}
void print() {
cout << "This is a cat. ";
Mammal::print();
}
};
int main() {
Mammal m("brown", 20.5);
Dog d("white", 12.3);
Cat c("black", 7.8);
Mammal* mp = new Mammal("gray", 15.2);
Dog* dp = new Dog("black and white", 8.7);
Cat* cp = new Cat("orange", 5.4);
cout << "Total count: " << Mammal::getCount() << endl;
m.print();
d.print();
c.print();
mp->print();
dp->print();
cp->print();
delete mp;
delete dp;
delete cp;
cout << "Total count: " << Mammal::getCount() << endl;
cout << "Main function ends." << endl;
return 0;
}
```
程序输出如下:
```
Total count: 6
Color: brown, Weight: 20.5
This is a dog. Color: white, Weight: 12.3
This is a cat. Color: black, Weight: 7.8
Color: gray, Weight: 15.2
This is a dog. Color: black and white, Weight: 8.7
This is a cat. Color: orange, Weight: 5.4
Total count: 3
Main function ends.
```
程序中定义了一个基类Mammal,以及两个派生类Dog和Cat。在Mammal中定义了color和weight数据成员和print虚函数,并且定义了静态成员count用来记录对象数量。在每个类的构造函数和析构函数中,都对count进行更新。Dog和Cat类中重载了print函数,输出自己特有的信息。在主函数中,使用new和delete创建和删除对象,输出count和各个对象的信息。最后输出"Main function ends."。
阅读全文