C++ initialize anonymous struct

2019-04-21 00:50发布

问题:

I'm still earning my C++ wings; My question is if I have a struct like so:

struct Height
{
    int feet;
    int inches;
};

And I then have some lines like so:

Height h = {5, 7};
Person p("John Doe", 42, "Blonde", "Blue", h);

I like the initialization of structs via curly braces, but I'd prefer the above be on one line, in an anonymous Height struct. How do I do this? My initial naive approach was:

Person p("John Doe", 42, "Blonde", "Blue", Height{5,7});

This didn't work though. Am I very far off the mark?

回答1:

You can't, at least not in present-day C++; the brace initialization is part of the initializer syntax and can't be used elsewhere.

You can add a constructor to Height:

struct Height
{
    Height(int f, int i) : feet(f), inches(i) { }
    int feet, inches;
};

This allows you to use:

Person p("John Doe", 42, "Blonde", "Blue", Height(5, 7));

Unfortunately, since Height is no longer an aggregate, you can no longer use the brace initialization. The constructor call initialization is just as easy, though:

Height h(5, 7);


回答2:

Standard C++ (C++98, C++03) doesn't support this.

g++ supports is a language extension, and I seem to recall that C++0x will support it. You'd have to check the syntax of the g++ language extension and/or possibly C++0x.

For currently standard C++, just name the Height instance, as you've already done, then use the name.

Cheers & hth.,