我还在学习C++;我的问题是,如果我有一个像这样的结构体:
struct Height
{
int feet;
int inches;
};
然后我有几行代码:
Height h = {5, 7};
Person p("John Doe", 42, "Blonde", "Blue", h);
我喜欢使用花括号初始化结构,但我更希望将其放在一行中,作为匿名Height结构。我该如何做到这一点?我的最初的幼稚方法是:
Person p("John Doe", 42, "Blonde", "Blue", Height{5,7});
然而,这并没有起作用。我离正确的方法很远吗?
Height{5,7}
,而是指定(struct Height){5,7}
(如果您是通过引用传递)(或者&(struct Height){5,7}
如果您是通过指针传递)。您基本上是将初始化列表转换为所需的类型。这是C99+的功能,但也应该适用于C ++。 - Erhhung