C++ 静态方法和静态属性

版权声明:博客注明来源即可。 https://blog.csdn.net/u014027680/article/details/83005107

来源:我的博客站 OceanicKang |《C++ 静态方法和静态属性》

#include <iostream>
#include <string>

class Pet
{
public:
	Pet(std::string name);
	virtual ~Pet();
	static int getCount();

protected:
	std::string name;

private:
	static int count;
};

class Cat : public Pet
{
public:
	Cat(std::string name);
};

int Pet::count = 0;

Pet::Pet(std::string name)
{
	this -> name = name;
	std::cout << "小猫" << name << "出生了\n";
	(this -> count)++;
}

Pet::~Pet()
{
	std::cout << "小猫" << this -> name << "死掉了\n";
	(this -> count)--;
}

int Pet::getCount()
{
    // 静态方法里不能访问非静态元素
	// 这里用 count 而不是 this -> count
	return count;
}

Cat::Cat(std::string name) : Pet(name)
{
	
}

int main()
{
	Cat cat_1("cat_1");
	Cat cat_2("cat_2");
	
	std::cout << "当前存活" << Pet::getCount() << "只\n";
	
	{
		Cat cat_3("cat_3");
		Cat cat_4("cat_4");
		
		std::cout << "当前存活" << Pet::getCount() << "只\n";
	}
	
	std::cout << "当前存活" << Pet::getCount() << "只\n";
	
	return 0;
}

1.JPG

  • 静态方法里不能使用非静态元素
  • 非静态方法里可以访问类的静态成员和非静态成员

猜你喜欢

转载自blog.csdn.net/u014027680/article/details/83005107