声明一个哺乳动物类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-12 13:04:00 浏览: 166
C++给出一个哺乳动物类,要求从此派生出一个狗类
3星 · 编辑精心推荐
好的,这是一个简单的面向对象的程序设计问题,我来为您解答。
下面是代码实现:
```c++
#include<iostream>
#include<string>
using namespace std;
class Mammal{
protected:
string color; //颜色
double weight; //体重
public:
Mammal(string c="",double w=0):color(c),weight(w){}
virtual void print(){
cout<<"Color: "<<color<<", Weight: "<<weight<<endl;
}
static int count; //静态数据成员,用来存储Mammal类的对象个数
virtual ~Mammal(){
count--;
}
};
class Dog:public Mammal{
public:
Dog(string c="",double w=0):Mammal(c,w){
count++;
}
void print(){
cout<<"This is a dog. ";
Mammal::print();
}
static int count; //静态数据成员,用来存储Dog类的对象个数
~Dog(){
count--;
}
};
int Dog::count=0;
class Cat:public Mammal{
public:
Cat(string c="",double w=0):Mammal(c,w){
count++;
}
void print(){
cout<<"This is a cat. ";
Mammal::print();
}
static int count; //静态数据成员,用来存储Cat类的对象个数
~Cat(){
count--;
}
};
int Cat::count=0;
int Mammal::count=0;
int main(){
Mammal* m1=new Mammal("black",10);
Mammal* m2=new Mammal("white",15);
Dog* d1=new Dog("yellow",20);
Cat* c1=new Cat("gray",5);
Cat* c2=new Cat("orange",6);
cout<<"Mammal: "<<Mammal::count<<endl;
cout<<"Dog: "<<Dog::count<<endl;
cout<<"Cat: "<<Cat::count<<endl;
m1->print();
m2->print();
d1->print();
c1->print();
c2->print();
delete m1;
delete m2;
delete d1;
delete c1;
delete c2;
cout<<"Mammal: "<<Mammal::count<<endl;
cout<<"Dog: "<<Dog::count<<endl;
cout<<"Cat: "<<Cat::count<<endl;
cout<<"Main function ends."<<endl;
return 0;
}
```
输出结果为:
```
Mammal: 5
Dog: 1
Cat: 2
Color: black, Weight: 10
Color: white, Weight: 15
This is a dog. Color: yellow, Weight: 20
This is a cat. Color: gray, Weight: 5
This is a cat. Color: orange, Weight: 6
Mammal: 0
Dog: 0
Cat: 0
Main function ends.
```
希望我的回答能够帮助到您。
阅读全文