【发布时间】:2019-08-08 14:30:49
【问题描述】:
我很困惑为什么这段代码会打印五次 5 而不是 1 2 3 4 5。 如果我把代码改成T t[4],那么输出就是4的四倍。
#include <iostream>
using namespace std;
class Test
{
static int x;
public:
Test() { x++; }
static int getX() {return x;}
};
int Test::x = 0;
int main()
{
Test t[5];
for (auto element : t)
{
cout << element.getX() << " ";
}
cout << endl;
return 0;
}
【问题讨论】:
-
调试器说什么?
-
因为有一个变量名为
Test::x。Tests 构造函数被调用 5 次,每次递增Test::x,结果为5。然后循环开始,Test::x(仍为5)被打印五次。