简体   繁体   English

初始化包含固定大小数组的 C++ 结构

[英]Initialize C++ struct that contains a fixed size array

Suppose I have a POD C struct as so:假设我有一个 POD C 结构,如下所示:

struct Example {
    int x;
    int y[10];
    int yLen;
}

With the following code, the program doesn't compile:使用以下代码,程序无法编译:

Example test() {
    int y[10];
    int yLen = 0;

    auto len = this->getSomethingLength();
    for (int i = 0; i < len; i++) {
        y[yLen++] = this->getSomething(i);
    }

    return Example{ 0, y, yLen };
}

However, doing return {0, {}, 0};但是,做return {0, {}, 0}; does seem to compile.似乎可以编译。 Problem is, I can't know the size of y until doing some sort of logic ahead of time.问题是,在提前做某种逻辑之前,我无法知道y的大小。 Initializing int y[10]{} in test doesn't seem to make a difference.test中初始化int y[10]{}似乎没有什么区别。 I know this seems like a pretty simple question, but I can't seem to find anything that works.我知道这似乎是一个非常简单的问题,但我似乎找不到任何有效的方法。

Declare the structure as a whole instead of its parts and then initialize it:将结构声明为一个整体而不是其部分,然后对其进行初始化:

Example test() {
    Example result;

    auto len = this->getSomethingLength();
    for (result.yLen = 0; result.yLen < len; result.yLen++) {
        result.y[result.yLen] = this->getSomething(result.yLen);
    }

    return result;
}

Declaring y as an int* and allocating memory with new , when the size is known, would be an even better solution.当大小已知时,将y声明为int*并使用new分配 memory 将是一个更好的解决方案。

Declare constructor in Example :Example中声明构造函数:

struct Example {
    int x;
    int y[10];
    int yLen;
    Example(int xNew, int *yNew, int yLenNew)
    {
        x = xNew;
        yLen = yLenNew;
        for (int i = 0; i < yLenNew; i++)
        {
            y[i] = yNew[i];
        }
    }
};

And use it like this:并像这样使用它:

Example test() {
    int y[10];
    int yLen = 0;

    auto len = this->getSomethingLength();
    for (int i = 0; i < len; i++) {
        y[yLen++] = this->getSomething(i);
    }

    return Example( 0, y, yLen );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM