<小甲鱼>C++实例练习19—记录猫狗数量(静态变量)
作者:互联网
前言:
参考:B站UP主鱼C_小甲鱼<C++快速入门>
代码调试平台:VS2017,调试成功。
问题描述:
问题描述:记录猫狗数量(静态变量)。
代码实现:
//静态变量static
#include<iostream>
#include <string>
using namespace std;
class Pet
{
public:
Pet(string theName);
~Pet();
static int getcount();
protected:
string name;
private:
static int count;
};
class Dog:public Pet
{
public:
Dog(string theName);
};
class Cat :public Pet
{
public:
Cat(string theName);
};
int Pet::count = 0; //为count分配了内存空间,并赋值
Pet::Pet(string theName)
{
name = theName;
count++;
cout << "一只动物出生了,名字是" <<name<<"\n"<< endl;
}
Pet::~Pet()
{
count--;
cout << name << "挂掉了。" << "\n" << endl;
}
int Pet::getcount()
{
return count;
}
Dog::Dog(string theName) :Pet(theName)
{
}
Cat::Cat(string theName) : Pet(theName)
{
}
int main()
{
Dog dog("Tom");
Cat cat("Jerry");
cout << "已经诞生了" << Pet::getcount() << "只动物。\n"<<endl;
{
Dog dog2("TP");
Cat cat1("je");
cout << "\n现在已经诞生了" << Pet::getcount() << "只宠物.\n" << endl;
}
cout << "现在还剩" << Pet::getcount() << "只宠物!\n";
return 0;
}
标签:count,string,19,Dog,C++,Cat,甲鱼,theName,Pet 来源: https://blog.csdn.net/weixin_48835182/article/details/115095666