Пространства имён
Варианты
Действия

Initializer list

Материал из cppreference.com

 
 
Язык С++
Общие темы
Управление программой
Операторы условного выполнения
Операторы повторения
Операторы перехода
Функции
объявление функции
объявление лямбда-функции
шаблон функции
спецификатор inline
спецификаторы исключений (устарело)
спецификатор noexcept (C++11)
Исключения
Пространства имён
объявление пространства имён
псевдонимы пространства имён
Типы
спецификатор decltype (C++11)
Спецификаторы
cv-спецификаторы
спецификаторы продолжительности хранения
спецификатор constexpr (C++11)
спецификатор auto (C++11)
спецификатор alignas (C++11)
Инициализация
Литералы
Выражения
Утилиты
Типы
typedef-объявление
объявление псевдонима типа (C++11)
атрибуты (C++11)
Приведения типов
неявные преобразования
const_cast-преобразование
static_cast-преобразование
dynamic_cast-преобразование
reinterpret_cast-преобразование
C-подобное и функциональное приведение типов
Выделение памяти
Классы
спецификатор friend
списки-инициализаторы
Особые свойства классовых функций
Специальные функции-члены
Шаблоны
шаблон класса
шаблон функции
специализация шаблона
упакованные параметры (C++11)
Разное
Ассемблерные вставки
 
(Не путать с зЬй :: initializer_list)
Original:
( Not to be confused with зЬй :: initializer_list )
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Они являются частью конструктор, который несет ответственность за член и предков инициализации
Original:
They are the part of a constructor which is responsible for member and ancestor initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[править] Синтаксис

constructor_signature : member_constructor_calls { constructor_body }

[править] Объяснение

Инициализатор список является местом, где инициализации объекта должно произойти, есть где конструкторы базовых классов и членов называется.
Original:
The initializer list is the place where initialization of the object should occur, there is where the constructors for base classes and members are called.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Пользователи инициализируются в том же порядке, как они были объявлены, а не как они появляются в списке инициализаторов.
Original:
Members are initialized in the same order as they are declared, not as they appear in 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.
Если параметр в конструктор имеет то же имя, как одного из членов, неоднозначность этот идентификатор передается в вызове конструктора внутри intializer список будет решен выбора параметра (а не член).
Original:
If a parameter in the constructor has the same name as one of the members, the ambiguity of that identifier being passed in a constructor call inside the intializer list is resolved choosing the parameter (and not the member).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Члены или базовых классов нет в списке будет построена по умолчанию
Original:
Members or base classes not present in the list will be default constructed
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[править] Пример

struct Class : public Base
{
    int x;
    int y;
 
    Class ( int x )
      : Base ( 123 ), // initialize base class
        x ( x ),      // x (member) is initialized with x (parameter)
        y ( 0 )       // y initialized to 0
    {}                // empty constructor body
 
    Class ( double a )
      : y ( a+1 ),
        x ( y ) // x will be initialized before y, this means that its value here is undefined
    {}          // No base class constructor in list, this is the same as calling Base()
 
    Class()
    try
      : Base ( 789 ),
        x ( 0 ),
        y ( 0 )
    {
        // no exception
    }
    catch (...)
    {
        // exception occurred on initialization
    }
};