Espacios de nombres
Variantes
Acciones

aggregate initialization

De cppreference.com
< cpp‎ | language

 
 
Lenguaje C++
Los temas generales
Original:
General topics
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Control de flujo
Original:
Flow control
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Sentencias condicionales ejecución
Original:
Conditional execution statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Instrucciones de iteración
Original:
Iteration statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ir declaraciones
Original:
Jump statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funciones
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaración de la función
lambda declaración de la función
función de plantilla
especificador inline
especificaciones de excepción (obsoleto)
noexcept especificador (C++11)
Excepciones
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los espacios de nombres
Original:
Namespaces
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
decltype specifier (C++11)
Los especificadores
Original:
Specifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
cv especificadores
almacenamiento duración especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialización
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los literales
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expresiones
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representaciones alternativas
Utilidades
Original:
Utilities
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
typedef declaration
alias de tipo de declaración (C++11)
atributos (C++11)
Lanza
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversiones implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-cast estilo y funcional
De asignación de memoria
Original:
Memory allocation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clases
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clase propiedades específicas de la función
Original:
Class-specific function properties
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funciones especiales miembro
Original:
Special member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Plantillas
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
clase de plantilla
función de plantilla
plantilla de especialización
paquetes de parámetros (C++11)
Varios
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Montaje en línea
 
Inicializa un agregado de braced-init-list
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.

Contenido

[editar] Sintaxis

T object = {arg1, arg2, ...}; (1)
T object {arg1, arg2, ...}; (2) (desde C++11)

[editar] Explicación

Inicialización de agregados es una forma de lista de inicialización, que inicializa los agregados'
Original:
Aggregate initialization is a form of lista de inicialización, 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.
Un agregado es un objeto del tipo que es uno de los siguientes
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.
  • tipo array
    Original:
    array type
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • tipo de clase (típicamente, struct o union), que tiene
    Original:
    class type (typically, struct or union), that has
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • ninguno de los miembros privados o protegidos
    Original:
    no private or protected members
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • no proporcionado por el usuario constructores
    Original:
    no user-provided constructors
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • no hay clases base
    Original:
    no base classes
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • ninguna de las funciones miembro virtuales
    Original:
    no virtual member functions
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • no hay inicializadores de llave-o-la igualdad de los miembros no estáticos
    Original:
    no brace-or-equal initializers for non-static members
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Los efectos de la inicialización de agregados son:
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.
  • Cada elemento de la matriz o no estático miembro de la clase, con el fin de subíndice de matriz / aparición en la definición de clase, es copia inicializada de la cláusula correspondiente de la lista de inicialización .
    Original:
    Each array element or non-static class member, in order of array subscript/appearance in the class definition, is copia inicializada 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.
  • Si la cláusula inicializador es una expresión, se permiten las conversiones implícitas, excepto (desde C++11) si se están reduciendo (como en lista de inicialización) .
    Original:
    If the initializer clause is an expression, implicit conversions are allowed, except (desde C++11) if they are narrowing (as in lista de inicialización).
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Si la cláusula inicializador es un anidado preparó-init-list, el miembro de la clase correspondiente en sí es un agregado: inicialización de agregados es recursiva .
    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.
  • Si el objeto es una matriz de tamaño desconocido, y el suministro llave cerrada en lista de inicialización tiene n cláusulas, el tamaño de la matriz es n
    Original:
    If the object is an array of unknown size, and the supplied brace-enclosed initializer list has n clauses, the size of the array is n
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Miembros de datos estáticos y anónimos campos de bits se pasan por alto durante la inicialización del total .
    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.
  • Si el número de cláusulas inicializador excede el número de miembros de inicializar, el programa está mal formada (error del compilador)
    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.
  • Si el número de cláusulas inicializador es menor que el número de miembros, los miembros restantes se inicializan mediante listas vacías, que realiza valor de inicialización. Si un miembro de un tipo de referencia es uno de estos miembros restantes, el programa está mal formada (referencias no pueden ser de valor inicializado)
    Original:
    If the number of initializer clauses is less than the number of members, the remaining members are initialized by empty lists, which performs valor de inicialización. 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.
  • Si la inicialización de agregados utiliza el formulario con el signo igual (T a = {args..}), las llaves alrededor del inicializador las listas anidadas pueden elidido (omitido), en cuyo caso, como las cláusulas de inicializador que sea necesario se utilizan para inicializar cada miembro o elemento de la correspondiente subagregado y las cláusulas inicializador posteriores se utilizan para inicializar los siguientes miembros del objeto. Sin embargo, si el objeto tiene un sub-conjunto sin miembros (un struct vacío o una estructura que sostiene sólo miembros estáticos), elisión llave no está permitido, y un {} vacío lista anidada debe ser utilizado .
    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.
  • Cuando un sindicato se inicializa inicialización de agregados, sólo el primer de sus miembros no estáticos de datos se inicializa .
    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.

[editar] Notas

Hasta C + 11, conversiones de restricción fueron permitidos en inicialización de agregados, pero se les permite ya no .
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.
Hasta C + 11, inicialización de agregados no se podría utilizar en una lista de inicialización del constructor debido a restricciones de sintaxis .
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.

[editar] Ejemplo

#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
 
}


[editar] Ver también