调用类里面的函数,需要对这个类进行实例化,但是有时候想要直接调用基类里面的数据,那么这个时候就可以使用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; }
原文链接: https://www.cnblogs.com/my-love-is-python/p/13341256.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/368346
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!