c++第七章-(静态属性和静态方法)

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 << "挂掉了
";
}

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 << "
已经诞生了" << Pet::getCount() << "只宠物!

" ;
    
    {//作用域的作用
        Dog dog2("Tom_2");
        Cat cat2("Jerry_2");
        
        std::cout << "
现在呢,已经诞生了" << Pet::getCount() << "只宠物!

" ;
    }

    std::cout << "
现在还剩下 "
    << Pet::getCount()
    << " 只宠物!

";
    
    return 0;
}

控制台返回的结果:

一只宠物出生了,名字叫做:Tom
一只宠物出生了,名字叫做:Jerry

已经诞生了2只宠物!

一只宠物出生了,名字叫做:Tom_2
一只宠物出生了,名字叫做:Jerry_2

现在呢,已经诞生了4只宠物!


现在还剩下 4 只宠物!

Jerry_2挂掉了
Tom_2挂掉了
Jerry挂掉了
Tom挂掉了

 2.this指针

  • this指针是类的一个自动生成、自动隐藏的私有成员,它存在于类的非静态成员函数中,指向被调用函数所在的对象的地址。
  • 当一个对象被创建时,该对象的this指针就自动指向对象数据的首地址。
  • 在程序运行时,对象的属性和方法都是保存在内存里,这意味着他们各自都有与之相关联的地址(对象的地址)。这些地址都可以通过指针来访问,而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
        << "
y="
        << 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
原文地址:https://www.cnblogs.com/huen/p/3823944.html