C++快速入门---静态属性和静态方法(15)

C++快速入门---静态属性和静态方法(15)

静态属性和静态方法

把一个或多个成员声明为属于某个类,而不是仅属于该类的对象。

好处1:程序员可以在没有创建任何对象的情况下调用有关的方法。

好处2:能够让有关的数据仍在该类的所有对象间共享。

代码如下:

#include <iostream>
#include <string>

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 <<"\n"; 
}

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()
{
	Dog dog("Tom");
	Cat cat("Jerry");
	
	std::cout << "\n已经诞生了" << Pet::getCount() << "只宠物!\n\n";
	
	{
		Dog dog_2("Tom_2");
		Cat cat_2("Jerry_2");
		
		std::cout << "\n现在呢,已经诞生了" << Pet::getCount() << "只宠物!\n\n";
	}
	
	std::cout << "\n现在还剩下" << Pet::getCount() << "只宠物!\n\n";
	
	return 0;
}

this指针

this指针是类的一个自动生成、自动隐藏的私有成员,它存在于类的非静态成员函数中,指向被调用函数所在的对象的地址。

当一个对象被创建时,该对象的this指针就自动指向对象数据的首地址。

#include <iostream>

class Point
{
private:
	int x, y;
public:
	Point(int a, int b)
	{
		x = a;
		y = b;
	}
	void MovePoint(int a, int b)
	{
		x = a;
		y = b;
	}
	void print()
	{
		std::cout << "x=" << x << "y=" << y << endl;
	}
};

int main()
{
	Point point1(10, 10);
	point1.MovePoint(2, 2);
	point1.print();
}

//当对象point1调用MovePoint(2, 2)时,即将point1对象的地址传递给了this指针

//MovePoint函数的原型事实上应该是 void MovePoint(Point *this, int a, int b);
//第一个参数是指向该类对象的一个指针,我们在定义成员函数时没看见是因为这个参数在类中是隐含的。

//这样point1的地址传递给了this,所以在MovePoint函数中便可以显示的写成:void MovePoint(int a, int b)
//{this->x = a, this->y = b;}
//即可以知道,point1调用该函数后,也就是point1的数据成员被调用并更新了值 

猜你喜欢

转载自blog.csdn.net/xiaodingqq/article/details/83660771