direct 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. |
Инициализирует объект из множества явных аргументов конструктора.
Original:
Initializes an object from explicit set of constructor arguments.
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 ( arg );
T object |
(1) | ||||||||
T object { arg };
T object |
(2) | (начиная с C++11) | |||||||
T ( other )
T |
(3) | ||||||||
static_cast< T >( other )
|
(4) | ||||||||
new T(args, ...)
|
(5) | ||||||||
Class::Class() : member(args, ...) {...
|
(6) | ||||||||
[arg](){...
|
(7) | (начиная с C++11) | |||||||
[править] Объяснение
Прямая инициализация выполняется в следующих ситуациях:
Original:
Direct initialization is performed in the following situations:
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.
1)
Инициализация с непустым скобки список выражений
Original:
initialization with a nonempty parenthesized list of expressions
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.
2)
во время выполнения последовательности Список инициализации, если не инициализатор-лист constuctors предоставляются и соответствие конструктор доступен, и все необходимые неявные преобразования не являются сужение.
Original:
during Список инициализации sequence, if no initializer-list constuctors are provided and a matching constructor is accessible, and all necessary implicit conversions are non-narrowing.
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.
3)
инициализации prvalue временными по функциональный оттенок или выражение в скобках список
Original:
initialization of a prvalue temporary by функциональный оттенок or with a parenthesized expression 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.
4)
инициализации prvalue временными по static_cast expession
Original:
initialization of a prvalue temporary by a static_cast expession
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.
5)
инициализации объекта с динамическим срок хранения новой выражения с непустым инициализатор
Original:
initialization of an object with dynamic storage duration by a new-expression with a non-empty initializer
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.
6)
инициализации базы или не статические члены конструктором инициализатор список
Original:
initialization of a base or a non-static member by constructor инициализатор список
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.
7)
инициализации закрытия объекта члена от переменных пойман экземпляр в лямбда-выражения
Original:
initialization of closure object members from the variables caught by copy in a lambda-expression
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:
The effects of direct 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.
- Если
Tэто класс, конструкторыTрассматриваются и лучший матч выбирается разрешение перегрузки. Конструктор затем вызывается для инициализации объекта.Original:IfTis a class type, the constructors ofTare examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- В противном случае, если
Tне является классом, стандартные преобразования используется, если необходимо, чтобы преобразовать значение other к CV-неквалифицированным версияT.Original:Otherwise, ifTis a non-class type, стандартные преобразования are used, if necessary, to convert the value of other to the cv-unqualified version ofT.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Notes
Прямая инициализация больше прав, чем копирование инициализации: копия инициализации рассматривает только без явных конструкторов и определяемые пользователем функции преобразования, в то время как прямой инициализации считает, что все конструкторы и неявные преобразования последовательностей.
Original:
Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non-explicit constructors and user-defined conversion functions, while direct-initialization considers all constructors and implicit conversion sequences.
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 <iostream> #include <memory> struct Foo { int mem; explicit Foo(int n) : mem(n) {} }; int main() { std::string s1("test"); // constructor from const char* std::string s2(10, 'a'); std::unique_ptr<int> p(new int(1)); // OK: explicit constructors allowed // std::unique_ptr<int> p = new int(1); // error: constructor is explicit Foo f(2); // f is direct-initialized: // constructor parameter n is copy-initialized from the rvalue 2 // f.mem is direct-initialized from the parameter n // Foo f2 = 2; // error: constructor is explicit std::cout << s1 << ' ' << s2 << ' ' << *p << ' ' << f.mem << '\n'; }
Вывод:
test aaaaaaaaaa 1 2