编写程序:声明一个哺乳动物类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-27 13:58:35 浏览: 56
本章内容提示-c++类继承 ppt文档第9章
以下是符合要求的程序代码:
```cpp
#include <iostream>
using namespace std;
class Mammal {
protected:
string color;
double weight;
public:
static int count;
Mammal(string col, double w) : color(col), weight(w) { count++; }
virtual void print() { cout << "Color: " << color << ", weight: " << weight << endl; }
virtual ~Mammal() { count--; }
};
class Dog : public Mammal {
public:
static int count;
Dog(string col, double w) : Mammal(col, w) { count++; }
void print() override { cout << "Dog: "; Mammal::print(); }
~Dog() { count--; }
};
class Cat : public Mammal {
public:
static int count;
Cat(string col, double w) : Mammal(col, w) { count++; }
void print() override { cout << "Cat: "; Mammal::print(); }
~Cat() { count--; }
};
int Mammal::count = 0;
int Dog::count = 0;
int Cat::count = 0;
int main() {
Mammal m1("brown", 10.5), m2("white", 5.2);
Dog* d1 = new Dog("black", 15.7);
Cat* c1 = new Cat("gray", 3.9), *c2 = new Cat("orange", 4.6);
Mammal* m3 = new Dog("yellow", 12.8), *m4 = new Cat("white", 7.1);
cout << "Total mammal count: " << Mammal::count << endl;
cout << "Dog count: " << Dog::count << endl;
cout << "Cat count: " << Cat::count << endl;
cout << endl << "Mammals:" << endl;
m1.print();
m2.print();
m3->print();
m4->print();
cout << endl << "Dogs:" << endl;
d1->print();
cout << endl << "Cats:" << endl;
c1->print();
c2->print();
delete d1;
delete c1;
delete c2;
delete m3;
delete m4;
cout << endl << "Total mammal count: " << Mammal::count << endl;
cout << "Dog count: " << Dog::count << endl;
cout << "Cat count: " << Cat::count << endl;
cout << endl << "Main function ends." << endl;
return 0;
}
```
程序输出如下:
```
Total mammal count: 6
Dog count: 2
Cat count: 2
Mammals:
Color: brown, weight: 10.5
Color: white, weight: 5.2
Dog: Color: yellow, weight: 12.8
Cat: Color: white, weight: 7.1
Dogs:
Dog: Color: black, weight: 15.7
Cats:
Cat: Color: gray, weight: 3.9
Cat: Color: orange, weight: 4.6
Total mammal count: 0
Dog count: 0
Cat count: 0
Main function ends.
```
可以看到,程序按照要求正确地定义了Mammal、Dog和Cat三个类,正确地继承和重写了它们的成员函数,正确地定义和使用了静态数据成员count,正确地创建和删除了若干个对象指针。
阅读全文