编写程序:声明一个哺乳动物类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-09 14:12:16 浏览: 14
以下是程序实现:
```cpp
#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 ~Mammal() { count--; }
virtual void print() { cout << "Color: " << color << ", Weight: " << weight << endl; }
static void printCount() { cout << "Total count: " << count << endl; }
};
class Dog : public Mammal {
public:
Dog(string c, double w) : Mammal(c, w) {}
~Dog() {}
void print() { cout << "Dog, "; Mammal::print(); }
};
class Cat : public Mammal {
public:
Cat(string c, double w) : Mammal(c, w) {}
~Cat() {}
void print() { cout << "Cat, "; Mammal::print(); }
};
int Mammal::count = 0;
int main() {
Mammal m1("Brown", 10.5);
Mammal m2("Black", 15.2);
Dog* d1 = new Dog("White", 7.8);
Cat* c1 = new Cat("Gray", 5.3);
Dog* d2 = new Dog("Yellow", 12.1);
Mammal::printCount();
m1.print();
m2.print();
d1->print();
c1->print();
d2->print();
delete d1;
delete c1;
delete d2;
Mammal::printCount();
cout << "Main function ends." << endl;
return 0;
}
```
输出结果:
```
Total count: 5
Color: Brown, Weight: 10.5
Color: Black, Weight: 15.2
Dog, Color: White, Weight: 7.8
Cat, Color: Gray, Weight: 5.3
Dog, Color: Yellow, Weight: 12.1
Total count: 2
Main function ends.
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)