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

New*_*bie 6 c++

我有一个结构:

struct something {
    int a, b, c, d;
};
Run Code Online (Sandbox Code Playgroud)

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

something var = {-1,-1,-1,-1};
Run Code Online (Sandbox Code Playgroud)

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

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

Gun*_*r47 13

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

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);
Run Code Online (Sandbox Code Playgroud)


小智 8

只需给struct一个构造函数:

struct something {
    int a, b, c, d;
    something() {
        a = b = c = d = -1;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后使用它:

int main() {
   something s;    // all members will  be set to -1
}
Run Code Online (Sandbox Code Playgroud)

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

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


Ala*_*lan 6

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

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

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

something foo;

foo.set_values(-1);
Run Code Online (Sandbox Code Playgroud)

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