C ++初始化匿名结构 [英] C++ initialize anonymous struct
问题描述
我仍然收获我的C ++翅膀;我的问题是如果我有这样的结构:
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});
这没有工作。
推荐答案
你不能,至少不是在今天的C ++中;
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.
您可以向 Height $ c $添加构造函数c:
You can add a constructor to Height
:
struct Height
{
Height(int f, int i) : feet(f), inches(i) { }
int feet, inches;
};
这允许您使用:
Person p("John Doe", 42, "Blonde", "Blue", Height(5, 7));
不幸的是,由于 Height
聚合,你不能再使用大括号初始化。构造函数调用初始化也很容易,但:
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);
这篇关于C ++初始化匿名结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!