为什么打印五次5而不是1 2 3 4 5?

neo*_*360 -1 c++ arrays object

我感到困惑,为什么此代码打印5次5而不是1 2 3 45。如果将代码更改为T t [4],则输出为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;
 }
Run Code Online (Sandbox Code Playgroud)

ζ--*_*ζ-- 5

x是静态的;的每个实例都Test具有相同的值。

Test t[5]声明并初始化时,Test()构造函数被调用五次;每个呼叫都会增加的一个共享值x。数组完全初始化后,x为5。

当您调用getX()每个元素时,它们都将返回该共享值。如果希望每个值都有自己的值,请递增,x但将递增的值分配给非静态成员变量:

class Test
{
    static int y;
    int x;
public:
    Test() { y++; x = y; }
    static int getX() {return x;}
};
Run Code Online (Sandbox Code Playgroud)