标签:style blog color 数据 c++ div
1.静态属性和静态方法
静态方法的调用,ClassName::mothodName();
class Pet { public: Pet(std::string theName); ~Pet(); static int getCount();//公开的静态方法 protected: std::string name; private: static int count;//私有的静态变量 }; class Dog:public Pet { public: Dog(std::string theName); }; class Cat:public Pet { public: Cat(std::string theName); }; int Pet::count = 0;//初始化静态变量 Pet::Pet(std::string theName) { name = theName; count++; std::cout << "一只宠物出生了,名字叫做:" << name << std::endl; } Pet::~Pet() { count--; std::cout << name << "挂掉了\n"; } int Pet::getCount() { return count; } Dog::Dog(std::string theName):Pet(theName) { } Cat::Cat(std::string theName):Pet(theName) { } int main(int argc, const char * argv[]) { Dog dog("Tom"); Cat cat("Jerry"); std::cout << "\n已经诞生了" << Pet::getCount() << "只宠物!\n\n" ; {//作用域的作用 Dog dog2("Tom_2"); Cat cat2("Jerry_2"); std::cout << "\n现在呢,已经诞生了" << Pet::getCount() << "只宠物!\n\n" ; } std::cout << "\n现在还剩下 " << Pet::getCount() << " 只宠物!\n\n"; return 0; }
控制台返回的结果:
一只宠物出生了,名字叫做:Tom 一只宠物出生了,名字叫做:Jerry 已经诞生了2只宠物! 一只宠物出生了,名字叫做:Tom_2 一只宠物出生了,名字叫做:Jerry_2 现在呢,已经诞生了4只宠物! 现在还剩下 4 只宠物! Jerry_2挂掉了 Tom_2挂掉了 Jerry挂掉了 Tom挂掉了
2.this指针
class Point { public: Point(int a,int b) { this->x = a; this->y = b; } ~Point() { std::cout << "this = " << this << std::endl;//打印this地址 } void MovePoint(int a,int b) { this->x = a; this->y = b; } void print() { std::cout << "x=" << this->x << "\ny=" << this->y << std::endl; } private: int x,y; }; int main(int argc, const char * argv[]) { Point point(10,10); std::cout << "point = " << &point << std::endl;//验证this指针与point是否同一个地址 point.MovePoint(2, 2);//其实传到时候是以MovePoint(&point,2, 2);的形式传过去,只不过是将第一个参数隐藏了 point.print(); return 0; }
控制台返回的结果:
point = 0x7fff5fbff8b8 x=2 y=2 this = 0x7fff5fbff8b8
c++第七章-(静态属性和静态方法),布布扣,bubuko.com
标签:style blog color 数据 c++ div
原文地址:http://www.cnblogs.com/huen/p/3823944.html