这是一道非常经典的练习题,涉及继承,静态变量,虚函数,友元的使用,统计动物数量
第一种方法:
#include <iostream>
using namespace std;
// 在此处补充你的代码
class Animal
{
protected:
static int number;
public:
Animal() {}
virtual ~Animal() {}//虚函数
friend void print();//一个类的友元函数可以访问该类的私有成员
}; int Animal::number = 0;//静态成员只能在类外初始化
class Dog : public Animal //继承
{
private:
static int number;
public:
Dog()//构造函数
{
Animal::number++;
number++;
}
~Dog()//析构函数
{
Animal::number--;
number--;
}
friend void print();
}; int Dog::number = 0;
class Cat: public Animal
{
private:
static int number;
public:
Cat()
{
Animal::number++;
number++;
}
~Cat()
{
Animal::number--;
number--;
}
friend void print();
}; int Cat::number = 0;
void print() {
cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
}
int main() {
print();
Dog d1, d2;
Cat c1;
print();
Dog* d3 = new Dog();
Animal* c2 = new Cat;
Cat* c3 = new Cat;
print();
delete c3;
delete c2;
delete d3;
print();
}
第二种方法:
#include <iostream>
using namespace std;
// 在此处补充你的代码
class Animal
{
public :
static int number;
Animal()
{
number++;
}
virtual ~Animal()如果不加virtual,删除c2的时候就不能调用Cat的析构函数了
{
number--;
}
};
class Dog:public Animal
{
public:
static int number;
Dog()
{
number++;
}
~Dog()
{
number --;
}
};
class Cat:public Animal
{
public:
static int number;
Cat()
{
number++;
}
~Cat()
{
number--;
}
};
int Animal::number=0,Dog::number=0,Cat::number=0;//静态成员变量只能在类外初始化,不能在里面。
void print() {
cout << Animal::number << " animals in the zoo, " << Dog::number << " of them are dogs, " << Cat::number << " of them are cats" << endl;
}
int main()
{
print();
Dog d1, d2;
Cat c1;
print();
Dog* d3 = new Dog();
Animal* c2 = new Cat;
Cat* c3 = new Cat;
print();
delete c3;
delete c2;
delete d3;
print();
}