在构造函数初始化器列表中使用大括号了解奇怪的语法 [英] Understanding the weird syntax with curly braces in a constructor initializer list
问题描述
因此遇到此问题时,我只是在浏览库的源代码。
So I was just browsing the source code of a library when I encountered this.
Font::Font(const sf::Font& font) :
m_font{std::make_shared<sf::Font>(font)}
{
}
我不理解语法
m_font{..}
这是什么?它有什么作用。如果这真是愚蠢的问题,我感到抱歉。我不知道该对Google使用什么,所以在这里问。
What is it? What does it do. I am sorry if this is really stupid question. I don't know what to Google, so asking here.
推荐答案
这在 cppreference ,但格式有点难以理解:
This is described on cppreference, but in a somewhat hard to read format:
在复合语句的大括号之前,任何构造函数的函数定义的主体可能包括成员初始化器列表,其语法为冒号
:
,然后是一个或多个 member-initializers 的逗号分隔列表,每个列表都有以下语法
The body of a function definition of any constructor, before the opening brace of the compound statement, may include the member initializer list, whose syntax is the colon character
:
, followed by the comma-separated list of one or more member-initializers, each of which has the following syntax
...
类或标识符大括号初始化列表(2)(自C ++ 11)
...
2)初始化由命名的基或成员 class-or-identifier 使用列表初始化(如果列表为空,则变为值初始化;初始化聚集时,聚合初始化门)
2) Initializes the base or member named by class-or-identifier using list-initialization (which becomes value-initialization if the list is empty and aggregate-initialization when initializing an aggregate)
这是要说的是 X :: X(...):some_member {some_expressions} {...}
导致 some_member
类成员从 some_expressions
。给定
What this is trying to say is that X::X(...) : some_member{some_expressions} { ... }
causes the some_member
class member to be initialised from some_expressions
. Given
struct X {
Y y;
X() : y{3} {}
};
数据成员 y
将被初始化完全相同,将初始化局部变量 Y y {3};
。
the data member y
will be initialised the exact same way a local variable Y y{3};
would be initialised.
在您的情况下, std :: make_shared< sf :: Font>(字体)
产生将用于初始化 m_font
类成员的值
In your case, std::make_shared<sf::Font>(font)
produces the value that will be used to initialise the m_font
class member.
这篇关于在构造函数初始化器列表中使用大括号了解奇怪的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!