C++基础-静态函数和静态变量(static)

调用类里面的函数,需要对这个类进行实例化,但是有时候想要直接调用基类里面的数据,那么这个时候就可以使用static对类的函数和变量进行声明

使用时,不需要进行类的声明 

静态函数只能调用静态变量 

#include <iostream>

using namespace std;

class Pet{
public:
    Pet(string theName);
    ~Pet();
    static int getCount();
protected:
    string name;
private:
    static int Count; //Count是私有属性,只能在类的内部被调用 
};

Pet::Pet(string theName) {
    name = theName;
    cout << "出生了" << name << endl;
    Count ++;
}

Pet::~Pet() {
    cout << "挂掉了" << name << endl;
    Count --;
}

int Pet::getCount() {
    return Count;
}

class Cat : public Pet{
public:
    Cat(string theName);
};

class Dog : public Pet{
public:
    Dog(string theName);
};

Cat::Cat(string theName) : Pet(theName){
}

Dog::Dog(string theName) : Pet(theName){

}

int Pet::Count = 0; //进行类的外部声明赋值 

int main() {
    Cat cat("Tom");
    Dog dog("Jerry");
    cout << "已经诞生了" << Pet::getCount() << endl;
    {
        Cat cat_1("Tom_1");
        Dog dog_1("Jerry_1");
        cout << "已经诞生了" << Pet::getCount() << endl; //因为对getCounter进行了static,因此不需要实例化 
    }
    cout << "当前的数量是" << Pet::getCount() << endl;

    return 0; 
}