编写程序:声明一个哺乳动物类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-19 18:58:40 浏览: 60
使用Animal和Mammal两个类来说明一般动物和哺乳动物的继承关系。C#代码[定义].pdf
5星 · 资源好评率100%
以下是程序代码:
```cpp
#include<iostream>
#include<string>
using namespace std;
class Mammal {
protected:
string color;
double weight;
public:
virtual void print() {
cout << "Color: " << color << endl;
cout << "Weight: " << weight << endl;
}
static int count;
Mammal(string c, double w) :color(c), weight(w) { count++; }
virtual ~Mammal() { count--; }
};
class Dog : public Mammal {
public:
static int count;
Dog(string c, double w) :Mammal(c, w) { count++; }
~Dog() { count--; }
void print() {
cout << "Dog's color: " << color << endl;
cout << "Dog's weight: " << weight << endl;
}
};
class Cat : public Mammal {
public:
static int count;
Cat(string c, double w) :Mammal(c, w) { count++; }
~Cat() { count--; }
void print() {
cout << "Cat's color: " << color << endl;
cout << "Cat's weight: " << weight << endl;
}
};
int Mammal::count = 0;
int Dog::count = 0;
int Cat::count = 0;
int main() {
Mammal* m1 = new Mammal("brown", 12.3);
Dog* d1 = new Dog("black", 7.8);
Cat* c1 = new Cat("white", 5.6);
Dog* d2 = new Dog("yellow", 10.4);
Mammal* m2 = new Dog("gray", 15.2);
cout << "Mammal count: " << Mammal::count << endl;
cout << "Dog count: " << Dog::count << endl;
cout << "Cat count: " << Cat::count << endl;
m1->print();
d1->print();
c1->print();
d2->print();
m2->print();
delete m1;
delete d1;
delete c1;
delete d2;
delete m2;
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: 5
Dog count: 3
Cat count: 1
Color: brown
Weight: 12.3
Dog's color: black
Dog's weight: 7.8
Cat's color: white
Cat's weight: 5.6
Dog's color: yellow
Dog's weight: 10.4
Dog's color: gray
Dog's weight: 15.2
Mammal count: 0
Dog count: 0
Cat count: 0
Main function ends.
```
程序首先定义了一个Mammal类,其中包含了颜色和体重的数据成员,以及一个虚函数print,用于输出颜色和体重的值。Mammal类还有一个静态变量count,用于存储Mammal对象的总数。
在Mammal类的派生类Dog和Cat中,分别定义了静态变量count,用于存储Dog和Cat对象的总数。Dog和Cat类还分别定义了构造函数和析构函数,在构造函数中对颜色和体重进行初始化,并执行count++语句,在析构函数中执行count--语句。此外,Dog和Cat类还重写了print函数,分别输出Dog和Cat对象的信息。
在主函数中,用一般方法定义了一个Mammal对象m1,两个Dog对象d1和d2,一个Cat对象c1,以及一个Mammal对象指针m2,指向一个Dog对象。程序中使用了new关键字创建了这些对象,并用delete关键字删除了它们。在不同的位置输出了各类对象的count值,并在最后输出了"Main function ends."。
阅读全文