静态属性和静态函数
#include <iostream> #include <string> class Pet { public: Pet(std::string theName); ~Pet(); void noget(void); static int getCount();//静态函数 /*就是只允许读取count的值,而不允许对count进行赋值等写入操作*/ static int getCount1()//全局函数 { a++; return a; } static int b; protected: std::string name; private: static int count; static int a;//静态属性 }; class Dog:public Pet { public: Dog(std::string theName); }; class Cat:public Pet { public: Cat(std::string theName); }; int Pet::count=0; int Pet::a=0; int Pet::b=0; /*注意初始化计数器为0 *上面该条语句进行了两项操作: *一个是申请了内存,一个是初始化操作 */ Pet::Pet(std::string theName) { name=theName; count++;/*注意这边在static函数内部进行操作, *有别于在main函数里(static函数外)进行。 *static函数外只允许进行读取操作。 */ std::cout<<"一只宠物出生了,叫做:"<<name<<"\n"; } void Pet::noget(void) { ; } Pet::~Pet() { count--; std::cout<<name<<"挂掉了\n"; } int Pet::getCount() { return count; } Cat::Cat(std::string theName):Pet(theName) { } Dog:: Dog(std::string theName):Pet(theName) { } int main() { Dog dog("Tom"); Cat cat("Jerry"); cat.noget(); Pet::b=1; std::cout<<cat.getCount1();//允许继承 std::cout<<Pet::getCount1(); //为什么这边需要在类里边getCount1()加个static才允许调用,变量b,函数noget()同样情况//
/*另解: 静态成员的最大特点就是没有this指针,因此可以通过作用域解析运算符(::)直接引用。当然也可以通过object.访问,可被派生类访问。摘自《高质量程序指南》*/
{ { Dog dog2("Tom2"); } Cat cat2("Jerry2"); std::cout<<"\n已经诞生了"<<Pet::getCount()<<"只宠物\n"; } //利用{}构建区域,一个{}相当于到离开括号时直接析构了 std::cout<<"\n 现在还剩"<<Pet::getCount()<<"只宠物\n"; return 0; }