关于类里的静态变量和函数里的静态变量的行为有些不理解。
我有这样一份代码,它是会 CE 的:
#include <bits/stdc++.h>
using namespace std;
template<typename T>
struct Counter
{
static T cnt;
Counter()=default;
inline void count()
{
cnt++,cout<<cnt<<endl;
}
};
int main()
{
Counter<int> x;
x.count();
x.count();
x.count();
return 0;
}
报错类似于 (.rdata$.refptr._ZN7CounterIiE3cntE[.refptr._ZN7CounterIiE3cntE]+0x0): undefined reference to 'Counter<int>::cnt'
我的理解是,静态的变量需要编译器分配内存,但是含有模板参数的类只有在实例化时才会真正构建,只有类的声明时不会分配内存的(事实上,没有模板参数的类结果也是一样的)。上面的代码加上一个 template<> int Counter<int>::cnt=0; 后可以通过编译,因为给变量分配了内存。
但是,如果我把声明放在函数 count 里,代码完美地通过了编译并输出了合理的东西:
#include <bits/stdc++.h>
using namespace std;
template<typename T>
struct Counter
{
Counter()=default;
inline void count()
{
static T cnt;
cnt++,cout<<cnt<<endl;
}
};
int main()
{
Counter<int> x;
x.count();
x.count();
x.count();
return 0;
}
输出:
1
2
3
但是,模板类的函数一样是在实例化时才真正构建,但为什么函数内部的静态变量可以直接使用?
有大佬解释一下上述现象,并告诉我类的静态成员变量和函数的静态变量行为的不同点吗?