STL笔记09 类模板遇上static关键字

我们知道在类中使用staitc关键字的时候,static不属于实例,而属于类本身。

但是在模板类中,作为类本身一开始无法初始化,所以static成员应该就不会属于类本身;
那么static关键字到底属于哪?

我们通过写一个小的示例程序来观察一下:

#include<iostream>
using namespace std;



template<class T>
class Person 
{
public:
	static int a;
};
//类外初始化
template<class T>int Person<T>::a = 0;


int main()
{
	//类模板具体化为int型
	Person<int>int_p1, int_p2, int_p3;
	Person<char>char_p1, char_p2, char_p3;

	int_p1.a = 10;
	char_p1.a = 100;

	cout << int_p1.a << " " << int_p2.a << " " << int_p3.a << endl;
	cout << int_p1.a << " " << char_p2.a << " " << char_p3.a << endl;
	return 0;
}

实验结果:
在这里插入图片描述
结论:
这说明static成员是属于类模板具体化的类,而不是类模板本身。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值