类的静态属性和静态方法

2019-04-15 15:39发布

#include #include using namespace std; class Pet { public: Pet(string); ~Pet(); static int getCount(void); //静态方法 protected: string name; private: static int count; //静态属性 }; class Dog : public Pet { public: Dog(string); }; class Cat : public Pet { public: Cat(string); }; Pet::Pet(string theName) { name = theName; cout << "宠物" << name << "诞生了!" << endl; count++; } Pet::~Pet() { count--; cout << "宠物" << name << "卒!" << endl; } int Pet::count = 0; //静态属性初始化 int Pet::getCount(void) { return count; } Dog::Dog(string theName) : Pet(theName) { cout << "小狗" << name << "诞生了!" << endl; } Cat::Cat(string theName) : Pet(theName) { cout << "小猫" << name << "诞生了!" << endl; } int main() { Dog dog("Tom"); Cat cat("Mike"); { Dog dog2("Holly"); Cat cat2("Jerry"); cout << "目前一共有" << Pet::getCount() << "只宠物!" << endl; //调用静态方法 } cout << "目前一共有" << Pet::getCount() << "只宠物!" << endl; return 0; }