gpt4 book ai didi

c++ - 如何将所有结构成员设置为相同的值?

转载 作者:可可西里 更新时间:2023-11-01 18:41:46 26 4
gpt4 key购买 nike

我有一个结构:

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);

关于c++ - 如何将所有结构成员设置为相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3173088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com