如何将多个值分配到一个struct一次

如何将多个值分配到一个struct一次

本文介绍了如何将多个值分配到一个struct一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以为一个结构美孚做这个初始化:

 富富= {一堆的,物联网,初始化};

不过,我不能做到这一点:

 富富;
富= {一堆的,物联网,初始化};

于是,两个问题:


  1. 为什么我不能做后者,仅用于初始化前一个特殊的构造?

  2. 我该怎么办类似第二个例子东西,即在code的单行声明一堆的结构变量它已经被初始化后?我试图避免诸多变数做到这一点对于大型结构:

     富富;foo.a = 1;
    foo.b = 2;
    foo.c的= 3;
    // ...循环往复



解决方案

首先是一个聚合初始化 - 你可以在那些读了,并在该解决方案已被标签初始化:

What被标记结构初始化语法?

这是一个特殊的初始化语法,你不能做你的结构初始化后类似的东西。你可以做的是提供一个成员(或非成员)函数把你的一系列的值作为参数,你再成员函数内分配 - 这将让你做到这一点的方式,同样的结构初始化后简洁(你写后的功能当然是第一次!)

I can do this on initialization for a struct Foo:

Foo foo =  {bunch, of, things, initialized};

but, I can't do this:

Foo foo;
foo = {bunch, of, things, initialized};

So, two questions:

  1. Why can't I do the latter, is the former a special constructor for initialization only?
  2. How can I do something similar to the second example, i.e. declare a bunch of variables for a struct in a single line of code after it's already been initialized? I'm trying to avoid having to do this for large structs with many variables:

    Foo foo;
    
    foo.a = 1;
    foo.b = 2;
    foo.c = 3;
    //... ad infinitum
    

解决方案

The first is an aggregate initializer - you can read up on those and tagged initializers at this solution:

What is tagged structure initialization syntax?

It is a special initialization syntax, and you can't do something similar after initialization of your struct. What you can do is provide a member (or non-member) function to take your series of values as parameters which you then assign within the member function - that would allow you to accomplish this after the structure is initialized in a way that is equally concise (after you've written the function the first time of course!)

这篇关于如何将多个值分配到一个struct一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:52