Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

c++ - how to assign multiple values into a struct at once?

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
    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

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

This will work if you have a good compiler (e.g. GCC). You might need to turn on C99 mode with --std=gnu99, I'm not sure.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...