C++继承和静态成员

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可以被任何类型进行替换,包括内置类型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值