类的静态属性和静态方法

版权声明:根号v587版权所有 https://blog.csdn.net/hcmdghv587/article/details/81867104
#include <iostream>
#include <string>
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;
}

猜你喜欢

转载自blog.csdn.net/hcmdghv587/article/details/81867104