C++ 构造函数将所有值设置为零

C++ Constructor setting all values to zero

struct AnimationData
{
    struct Frame
    {
        int x1, y1, x2, y2;
        float dt; // seconds
        Frame() : x1(0), y1(0), x2(1), y2(1), dt(1) {}
    } * frames;

    int frame_count;

    std::string name;

    AnimationData(int fc, std::string n) : frame_count(fc), name(n)
    {
        frames = new Frame[fc];
        for (int i = 0; i < fc; i++)
        {
            std::cout << frames[i].x2 << '\n';
        }
    }
};

int main()
{

    AnimationData data{10, "test"};
    data.frames[1].x1 = 666;

    std::cout << "Start" << '\n';
    for (int i = 0; i < data.frame_count; i++)
    {
        std::cout << data.frames[i].x1 << '\n';
    }

    return 0;
}

这输出:

1
1
1
1
1
1
1
1
1
1
Start
0
666
0
0
0
0
0
0
0
0

为什么除了我设置的那个以外,它把所有东西都归零了? (请注意,如果与此相关,我对复制和移动构造函数一无所知)

Why Does it turn everything to zero except for the one I set?

因为默认构造函数Frame::Frame()会将x1y1初始化为0x2y2dt1 当你写:

frames = new Frame[fc]; //default ctor will initialize x1, y1 to 0 and x2, y2, dt to 1

也就是说,将使用 Frame 默认构造函数 创建将在堆上分配的 10 Frame 个对象这会将 x1y1 初始化为 0 以及 x2y2dt1。这就是为什么当你写道:

std::cout << frames[i].x2 << '\n'; //prints 1 becasue default ctor initialized `x2` to `1`

上面的语句将打印 1 as default ctor initialized x2 to 1

出于同样的原因,当你写:

std::cout << data.frames[i].x1 << '\n'; //will print 0 as default ctro initialized x1 to 0 except for `data.frames[1].x1` which you set to `666`.

上面的语句将打印 0,因为默认 ctor 将 x1 初始化为 0,除了 data.frames[1].x1,您专门设置为 666

您可以通过在其中添加 cout 语句来确认使用了默认的 ctor,如下所示:

Frame() : x1(0), y1(0), x2(1), y2(1), dt(1) {
        std::cout<<"default ctor called"<<std::endl;
    }

修改后的output程序为:

default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
1
1
1
1
1
1
1
1
1
1
Start
0
666
0
0
0
0
0
0
0
0