类模板碰到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>ip1, ip2, ip3;
    Person<char>cp1, cp2, cp3;

    ip1.a = 10;
    cp1.a = 100;

    cout << ip1.a << " " << ip2.a << " " << ip2.a << endl;
    cout << cp1.a << " " << cp2.a << " " << cp2.a << endl;
    return 0;
}

运行结果:

10 10 10
100 100 100

这说明static成员是属于类模板具体化的类,而不是类模板本身。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章