基类定义了static成员,则整个继承体系里面只有一个这样的成员。无论派生出多少个子类,都只有一个static成员实例。

#include<iostream>

#include<string.h>

using namespace std;

class Person

{

public:

Person()

{

++_count;

}

protected:

string _name;          // 姓名

string _sex;           // 性别

int _age;              // 年龄


public:

static int _count;     // 统计人的个数。

};


int Person::_count = 0;


class Student : public Person

{

protected:

int _stuNum;      // 学号

};


class Graduate : public Student

{

protected:

string _seminarCourse;     // 研究科目

};


void TestPerson1()

{

Student s1;

Student s2;

Student s3;


Graduate s4;


cout << " 人数 :" << Person::_count << endl;//输出4;



Student::_count = 0;


cout << " 人数 :" << Person::_count << endl;//输出0;

}

int main()

{

TestPerson1();

return 0;


}

输出4和0;