繁体   English   中英

如何将所有struct成员设置为相同的值?

[英]How to set all struct members to same value?

我有一个结构:

struct something {
    int a, b, c, d;
};

是否有一些简单的方法可以将所有a,b,c,d设置为某个值,而无需单独键入它们:

something var = {-1,-1,-1,-1};

还有太多重复(假设结构有30个成员...)

我听说过“构造”或其他东西,但我想在代码的不同部分将这些值设置为其他值。

这是我对这个问题的第二个答案。 第一个按照你的要求做了,但正如其他评论员指出的那样,这不是正确的做事方式,如果你不小心的话可能让你陷入困境。 相反,这里是如何为您的结构编写一些有用的构造函数:

struct something {
    int a, b, c, d;

    // This constructor does no initialization.
    something() { }

    // This constructor initializes the four variables individually.
    something(int a, int b, int c, int d) 
        : a(a), b(b), c(c), d(d) { }

    // This constructor initializes all four variables to the same value
    something(int i) : a(i), b(i), c(i), d(i) { }

//  // More concise, but more haphazard way of setting all fields to i.
//  something(int i) {
//      // This assumes that a-d are all of the same type and all in order
//      std::fill(&a, &d+1, i);
//  }

};

// uninitialized struct
something var1;

// individually set the values
something var2(1, 2, 3, 4);

// set all values to -1
something var3(-1);

只需给struct一个构造函数:

struct something {
    int a, b, c, d;
    something() {
        a = b = c = d = -1;
    }
};

然后使用它:

int main() {
   something s;    // all members will  be set to -1
}

您还可以使用构造函数重置成员:

int main() {
   something s;    // all members will  be set to -1
   s.a = 42;   
   s = something();  // reset everything back to -1
}

您可以为结构定义方法。 那么为什么不呢:

struct something {
    int a, b, c, d;

    void set_values(int val) 
    { 
      a = b = c = d = val;
    }
};

something foo;

foo.set_values(-1);

它绝对值得一提的是@sbi在评论中提出的观点:如果你的目的是初始化结构,那么你应该使用构造函数。 您应该避免允许结构/对象的用户将其置于不可用/错误状态。

在我收集的时候,你希望你的结构保持POD但仍然希望有一些“方便构造函数”。
在这种情况下添加构造函数不会起作用,因为你丢失了POD-ness,因此我使用了一个辅助函数:

something make_something() {
    something s = { -1, -1, -1, -1};
    return s;
}

如果要将其设置为不同的值,请让该函数采用可能的可选参数:

something make_something(int i = 0) {
     something s = { i, i, i, i };
     return s;
} 

现在,您可以将定义和初始化简化为一行:

something s = make_something(-1);

建立结构和数组的联合。 并使用循环初始化数组。

union something {
    struct {
       int a,b,c,d;
    };
    int init[4];
};

   something truc;
   for (int i=0; i<4; i++) truc.init[i] = -1;

如果你有

struct
{int a,b,c.......;}foo;

我写了那段代码,似乎工作正常:

int* pfoo;
for (int i = 0; i < sizeof(foo); i++)
{
    pfoo = (int*)((int)(&foo) + i*sizeof(int));
    *pfoo = f(i/2); //set the values (here: the values of a random function f)
}

它直接从&foo开始写入内存(结构中第一个变量的地址)

暂无
暂无

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

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