Dog类和Cat类分别继承Animal类; Animal类、Dog类和Cat类各有一个默认构造函数,分别输出字符串“Animal”“Dog”和“Cat”;一个析构函数在类中添加静态数据成员,用于运行时计算所有Animal,Dog和Cat类对象的数量; 在各类中添加静态函数成员getcount0函数,用于分别显示Animal,Dog和Cat类对象的数量;在Animal类中定义抽象方法 speak0
时间: 2023-05-15 20:08:12 浏览: 151
类的各种函数
Animal类中定义的抽象方法 speak0可以被子类Dog类和Cat类重写,用于输出不同的动物叫声。以下是完整的代码实现:
```cpp
#include <iostream>
class Animal {
public:
virtual void speak0() = 0; // 抽象方法
static int count0; // 静态数据成员
Animal() {
std::cout << "Animal" << std::endl;
count0++;
}
virtual ~Animal() {
count0--;
}
static void getcount0() {
std::cout << "Animal count: " << count0 << std::endl;
}
};
class Dog : public Animal {
public:
void speak0() override {
std::cout << "Woof!" << std::endl;
}
Dog() {
std::cout << "Dog" << std::endl;
count0++;
}
~Dog() {
count0--;
}
static void getcount0() {
std::cout << "Dog count: " << count0 << std::endl;
}
};
class Cat : public Animal {
public:
void speak0() override {
std::cout << "Meow!" << std::endl;
}
Cat() {
std::cout << "Cat" << std::endl;
count0++;
}
~Cat() {
count0--;
}
static void getcount0() {
std::cout << "Cat count: " << count0 << std::endl;
}
};
int Animal::count0 = 0;
int main() {
Animal* a1 = new Dog();
Animal* a2 = new Cat();
Animal::getcount0();
Dog::getcount0();
Cat::getcount0();
a1->speak0();
a2->speak0();
delete a1;
delete a2;
Animal::getcount0();
Dog::getcount0();
Cat::getcount0();
return 0;
}
```
输出结果为:
```
Animal
Dog
Animal
Cat
Animal count: 2
Dog count: 1
Cat count: 1
Woof!
Meow!
Animal count: 0
Dog count: 0
Cat count: 0
```
阅读全文