6.1静态成员不分裂
继承与静态成员,静态成员只有一个,所有对象共享(包括基类对象和派生类对象)。
class Person
{
protected:
static int num; // 个数
private:
public:
Person() {}
~Person() {}
};
int Person::num = 0;
class Student : public Person
{
private:
public:
Student()
{
cout << "create student: "<< (num += 1) << endl;
}
~Student()
{
cout << "Destroy student: "<< (num -= 1) << endl;
}
};
class Employee : public Person
{
private:
public:
Employee()
{
cout << "Create Employee : " << (num += 1) << endl;
}
~Employee()
{
cout <<"Destroy Employee : "<< (num -= 1) << endl;
}
};
int main()
{
Student s1, s2, s3;
Employee e1, e2;
return 0;
}
总结:Person 基类中设计了static静态成员 num ,在基类外初始化。则整个继承体系里面只有一个静态num成员。无论派生出多少个子类,都只有一个static成员实例。
6.2静态成员分裂
template<class T>
class Person
{
protected:
static int num; // 个数
private:
public:
Person() {}
~Person() {}
};
template<class T>
int Person<T>::num = 0;
class Student : public Person<Student>
{
private:
public:
Student()
{
cout << "create student: "<< (num += 1) << endl;
}
~Student()
{
cout << "Destroy student: "<< (num -= 1) << endl;
}
};
class Employee : public Person<Employee>
{
private:
public:
Employee()
{
cout << "Create Employee : " << (num += 1) << endl;
}
~Employee()
{
cout <<"Destroy Employee : "<< (num -= 1) << endl;
}
};
int main()
{
Student s1, s2, s3;
Employee e1, e2;
return 0;
}
原因:模板是产生代码的代码,模板Person类会分裂成两个实例化的类
Student类在继承时是以左边的实例化类为基类进行继承,Employee类在继承时是以右边的实例化类为基类进行继承的,二者的num是不同的num。
但如果Student类和Employee类继承的实例化类型相同,则num依然是同一个num。即:
class A
{};
class Student : public Person<A>
{
private:
public:
Student()
{
cout << "create student: "<< (num += 1) << endl;
}
~Student()
{
cout << "Destroy student: "<< (num -= 1) << endl;
}
};
class Employee : public Person<A>
{
private:
public:
Employee()
{
cout << "Create Employee : " << (num += 1) << endl;
}
~Employee()
{
cout <<"Destroy Employee : "<< (num -= 1) << endl;
}
};
int main()
{
Student s1, s2, s3;
Employee e1, e2;
return 0;
}
A可以被任何类型进行替换,包括内置类型