//test.cpp
#include <iostream.h>
#include "cat.h"
//忘记为静态类成员初始化将导致编译错误
int Cat::HowManyCats = 0;
void main()
{
const int MaxCats = 5;
Cat * CatHouse[MaxCats];
for(int i=0; i<MaxCats; i++)
CatHouse[i] = new Cat(i);
for( i=0; i<MaxCats; i++)
{
cout << "There are ";
cout << Cat::HowManyCats;
cout << " cats left!\t" ;
cout << "Deleting the one which is ";
cout << CatHouse[i] -> GetAge();
cout << " years old." << endl;
delete CatHouse[i];
CatHouse[i] = 0;
}
}
//cat.h
#include <iostream.h>
class Cat
{
public:
Cat(int age):itsAge(age){HowManyCats++;}
virtual ~Cat(){HowManyCats--;}
virtual int GetAge()const {return itsAge;}
virtual void SetAge(int age) { itsAge = age;}
static int HowManyCats; //注意1:此处为公有
//注意2:静态数据成员的声明处,不能初始化
private:
int itsAge;
};
#include <iostream.h>
#include "cat.h"
//忘记为静态类成员初始化将导致编译错误
int Cat::HowManyCats = 0;
void main()
{
const int MaxCats = 5;
Cat * CatHouse[MaxCats];
for(int i=0; i<MaxCats; i++)
CatHouse[i] = new Cat(i);
for( i=0; i<MaxCats; i++)
{
cout << "There are ";
cout << Cat::HowManyCats;
cout << " cats left!\t" ;
cout << "Deleting the one which is ";
cout << CatHouse[i] -> GetAge();
cout << " years old." << endl;
delete CatHouse[i];
CatHouse[i] = 0;
}
}
//cat.h
#include <iostream.h>
class Cat
{
public:
Cat(int age):itsAge(age){HowManyCats++;}
virtual ~Cat(){HowManyCats--;}
virtual int GetAge()const {return itsAge;}
virtual void SetAge(int age) { itsAge = age;}
static int HowManyCats; //注意1:此处为公有
//注意2:静态数据成员的声明处,不能初始化
private:
int itsAge;
};