zoukankan      html  css  js  c++  java
  • 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; 
    }
  • 相关阅读:
    5.7填数字游戏求解
    5.6判断回文数字
    5.5百钱买百鸡问题
    5.4三色球问题
    5.3哥德巴赫猜想的近似证明
    5.2求两个数的最大公约数和最小公倍数
    5.1舍罕王的失算
    4.19递归反向输出字符串
    Elasticsearch 安装
    linux 安装nginx步骤
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/13341256.html
Copyright © 2011-2022 走看看