我无法理解以下代码的输出:-
#include <iostream>
using namespace std;
template <typename T>
void fun(const T&x){
static int count = 0;
cout << "x = " << x << " count = " << count << endl;
++count;
return;
}
int main(){
fun(1);
fun('A');
fun(1.1);
fun(2.2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Output:-
x = 1 count = 0
x = A count = 0
x = 1.1 count = 0
x = 2.2 count = 1
Run Code Online (Sandbox Code Playgroud)
如果每次调用函数时都将静态变量 count 的值重新分配为 0,那么为什么在第四次调用该函数时它会变为 1。还有一件事,我们不能直接传递“T x”而不是“ const T&x …