【发布时间】:2016-06-06 06:27:36
【问题描述】:
这是一个来自 geeksforgeeks 的示例。下面的代码我看不懂。
template<class T> int Test<T>::count = 0;
count 是一个外部变量吗?为什么不让 static int count = 0? geeksforgeeks 中的描述和代码如下。
类模板和静态变量:类模板的规则是 与函数模板相同 类模板的每个实例化都有 它自己的成员静态变量副本。例如,在下面 程序有两个实例Test和Test。所以静态的两个副本 变量计数存在。
#include <iostream>
using namespace std;
template <class T> class Test
{
private:
T val;
public:
static int count;
Test()
{
count++;
}
// some other stuff in class
};
template<class T>
int Test<T>::count = 0;
int main()
{
Test<int> a; // value of count for Test<int> is 1 now
Test<int> b; // value of count for Test<int> is 2 now
Test<double> c; // value of count for Test<double> is 1 now
cout << Test<int>::count << endl; // prints 2
cout << Test<double>::count << endl; //prints 1
getchar();
return 0;
}
【问题讨论】: