{}:打包作用,限定变量的范围。
在main函数中,单独的{}限定了dog_2与cat_2的范围,当运行到 ‘}’ 时,自动调用Dog与Cat的析构函数,释放Dog与Cat
#include <iostream>
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";
{
Dog dog_2("dog_02");
Cat cat_2("cat_2");
std::cout << "\n已经诞生了" << Pet::getCount() << "只宠物\n";
}
std::cout <<"\n一共"<<Pet::getCount()<<"个宠物\n";
}