aggregate initialization
Материал из cppreference.com
|
|
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Инициализирует совокупного от фигурных-Init-лист
Original:
Initializes an aggregate from braced-init-list
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Содержание |
[править] Синтаксис
T object = {arg1, arg2, ...};
|
(1) | ||||||||
T object {arg1, arg2, ...};
|
(2) | (начиная с C++11) | |||||||
[править] Объяснение
Совокупный инициализации формы Список инициализации, который инициализирует' агрегатов
Original:
Aggregate initialization is a form of Список инициализации, which initializes aggregates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Агрегат является объектом типа, что является одним из следующего
Original:
An aggregate is an object of the type that is one of the following
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
- тип массиваOriginal:array typeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Класс типа (как правило, struct или union), что имеетOriginal:class type (typically, struct or union), that hasThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- нет частных или защищенных членовOriginal:no private or protected membersThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - не предоставленные пользователем конструкторовOriginal:no user-provided constructorsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - нет базовых классовOriginal:no base classesThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - нет виртуальных функций-членовOriginal:no virtual member functionsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - не скобкой или равно инициализаторы для нестатических членовOriginal:no brace-or-equal initializers for non-static membersThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
Влияние совокупного инициализации являются:
Original:
The effects of aggregate initialization are:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
- Каждый элемент массива или нестатический член класса, в порядке индекса массива / появление в определении класса, является Копия инициализации из соответствующего пункта из списка инициализации.Original:Each array element or non-static class member, in order of array subscript/appearance in the class definition, is Копия инициализации from the corresponding clause of the initializer list.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Если инициализатор предложение является выражением, неявные преобразования допускается, за исключением (начиная с C++11), если они сужаются (как в Список инициализации).Original:If the initializer clause is an expression, implicit conversions are allowed, except (начиная с C++11) if they are narrowing (as in Список инициализации).The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Если инициализатор пунктом является вложенной приготовился-INIT-лист, член-корреспондент класс сам совокупности: совокупность инициализации рекурсивных.Original:If the initializer clause is a nested braced-init-list, the corresponding class member is itself an aggregate: aggregate initialization is recursive.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Если объект является массив неизвестного размера, и поставляется фигурные скобки инициализатор список имеет
nположения, размера массиваnOriginal:If the object is an array of unknown size, and the supplied brace-enclosed initializer list hasnclauses, the size of the array isnThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Статические данные-члены и анонимные битовые поля пропускаются во время групповой инициализации.Original:Static data members and anonymous bit-fields are skipped during aggregate initialization.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Если количество инициализаторов пунктов превышает количество членов для инициализации, программа плохо сформированных (ошибка компилятора)Original:If the number of initializer clauses exceeds the number of members to initialize, the program is ill-formed (compiler error)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Если количество инициализаторов пунктов меньше, чем число членов, остальные члены инициализируются пустыми списками, которая выполняет Значение инициализации. Если член ссылочного типа является одним из этих остальных членов, программа плохо сформированных (ссылки не может быть инициализирован значением)Original:If the number of initializer clauses is less than the number of members, the remaining members are initialized by empty lists, which performs Значение инициализации. If a member of a reference type is one of these remaining members, the program is ill-formed (references cannot be value-initialized)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Если совокупный инициализации используется форма со знаком равенства (T a = {args..}), фигурные скобки вложенные списки инициализации могут быть опущены (опущено), в этом случае, так как многие положения инициализатор по мере необходимости используются для инициализации каждого члена или элемент соответствующего subaggregate, и последующие пункты инициализатор используются для инициализации следующие члены объекта. Однако, если объект имеет суб-агрегата без членов (пустой структуры или структуры холдинга только статические члены), скобки элизии не допускается, и пустой вложенных
{}список должен быть использован.Original:If the aggregate initialization uses the form with the equal sign (T a = {args..}), the braces around the nested initializer lists may be elided (omitted), in which case, as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object. However, if the object has a sub-aggregate without any members (an empty struct, or a struct holding only static members), brace elision is not allowed, and an empty nested list{}must be used.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Когда союз инициализируется агрегатную инициализацию, только ее первый не-статических данных инициализируется.Original:When a union is initialized by aggregate initialization, only its first non-static data members is initialized.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Notes
До C + +11, сужающие преобразования были разрешены в совокупности инициализации, но они больше не позволили.
Original:
Until C++11, narrowing conversions were permitted in aggregate initialization, but they are no longer allowed.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
До C + +11, совокупный инициализации не может быть использована в списке инициализации конструктора в связи с ограничениями синтаксиса.
Original:
Until C++11, aggregate initialization could not be used in a constructor initializer list due to syntax restrictions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Пример
#include <string> #include <array> struct S { int x; struct Foo { int i; int j; int a[3]; } b; }; union U { int a; const char* b; }; int main() { S s1 = { 1, { 2, 3, {4, 5, 6} } }; S s2 = { 1, 2, 3, 4, 5, 6}; // same, but with brace elision S s3{1, {2, 3, {4, 5, 6} } }; // same, using direct-list-initialization syntax // S s4{1, 2, 3, 4, 5, 6}; // error: brace-elision only allowed with equals sign int ar[] = {1,2,3}; // ar is int[3] // char cr[3] = {'a', 'b', 'c', 'd'}; // too many initializer clauses char cr[3] = {'a'}; // array initialized as {'a', '\0', '\0'} int ar2d1[2][2] = {{1, 2}, {3, 4}}; // fully-braced 2D array: {1, 2} // {3, 4} int ar2d2[2][2] = {1, 2, 3, 4}; // brace elision: {1, 2} // {3, 4} int ar2d3[2][2] = {{1}, {2}}; // only first column: {1, 0} // {2, 0} std::array<int, 3> std_ar2{ {1,2,3} }; // std::array is an aggregate std::array<int, 3> std_ar1 = {1, 2, 3}; // brace-elision okay int ai[] = { 1, 2.0 }; // narrowing conversion from double to int: // error in C++11, okay in C++03 std::string ars[] = {std::string("one"), // copy-initialization "two", // conversion, then copy-initialization {'t', 'h', 'r', 'e', 'e'} }; // list-initialization U u1 = {1}; // OK, first member of the union // U u2 = { 0, "asdf" }; // error: too many initializers for union // U u3 = { "asdf" }; // error: invalid conversion to int }