Default constructors
De 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. |
Un constructor predeterminado es un constructor que se puede llamar sin argumentos (ya sea definida con una lista de parámetros vacía, o con argumentos por defecto proporcionados para cada parámetro). Un tipo con un constructor público predeterminado es
DefaultConstructible
.Original:
A default constructor is a constructor which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter). A type with a public default constructor is
DefaultConstructible
.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.
Contenido |
[editar] Sintaxis
ClassName ( ) ;
|
(1) | ||||||||
ClassName :: ClassName ( ) body
|
(2) | ||||||||
ClassName() = delete ;
|
(3) | (desde C++11) | |||||||
ClassName() = default ;
|
(4) | (desde C++11) | |||||||
[editar] Explicación
1)
La declaración de un constructor por defecto
Original:
Declaration of a default 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.
2)
Definición del constructor fuera del cuerpo de la clase
Original:
Definition of the constructor outside the class body
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)
La inhibición de la generación automática de un constructor predeterminado
Original:
Inhibiting the automatic generation of a default 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.
4)
Explícitamente obligando a la generación automática de un constructor por defecto
Original:
Explicitly forcing the automatic generation of a default 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.
ClassName
es el identificador de la clase envolventeOriginal:
ClassName
is the identifier of the enclosing classThe 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.
Los constructores por defecto se llama cuando:
Original:
The default constructors are called when:
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.
- la creación de objetos o arrays de duración estática, almacenamiento local de subprocesos y automático que se declaran sin un inicializador, (T obj; o T arr[10];)Original:creating objects or arrays of static, thread-local, and automatic storage duration that are declared without an initializer, (T obj; or T arr[10];)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - la creación de objetos de tiempo de almacenamiento dinámico cuando la nueva expresión-se escribe sin un inicializador (new T;)Original:creating objects of dynamic storage duration when the new-expression is written without an initializer (new T;)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - la creación de matrices de tiempo de almacenamiento dinámico con el new T[n] expresiónOriginal:creating arrays of dynamic storage duration with the expression new T[n]The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - la creación de valor inicializados los objetos temporales con la expresión de conversión T() .Original:creating value-initialized temporary objects with the cast expression T().The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[editar] Implícitamente, declarado constructor predeterminado
Si no hay constructores definidos por el usuario de cualquier tipo se proporcionan para un tipo de clase (struct, class o union), el compilador siempre declarar un constructor por defecto como miembro
inline public
de su clase. Si algunos constructores definidos por el usuario están presentes, el usuario todavía puede forzar la generación del constructor implícitamente declarado con la palabra default
(desde C++11) .Original:
If no user-defined constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an
inline public
member of its class. If some user-defined constructors are present, the user may still force the generation of the implicitly declared constructor with the keyword default
(desde C++11).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.
[editar] Suprimido constructor implícitamente-declaró el default
El constructor por defecto implícitamente declaradas o cesación de pagos por
T
clase es (hasta C++11) undefined / define como borrado (desde C++11) si alguna de las siguientes situaciones:Original:
The implicitly-declared or defaulted default constructor for class
T
is undefined (hasta C++11) / defined as deleted (desde C++11) if any of the following is true: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
tiene un elemento de tipo de referencia (sin un apoyo-o-igual initializer(desde C++11)) .Original:T
has a member of reference type (without a brace-or-equal initializer(desde C++11)).The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
T
tiene un miembro de const (sin una abrazadera initializer(desde C++11)-o-igual) o definido por el usuario constructor predeterminado .Original:T
has a const member (without a brace-or-equal initializer(desde C++11)) or a user-defined default constructor.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
T
tiene un miembro (sin una abrazadera initializer(desde C++11)-o-igual), que tiene un constructor predeterminado eliminada, o su constructor predeterminado es ambiguo o inaccesibles de este constructor .Original:T
has a member (without a brace-or-equal initializer(desde C++11)), which has a deleted default constructor, or its default constructor is ambiguous or inaccessible from this constructor.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
T
tiene una base directa o virtual que tiene un constructor predeterminado eliminado, o es ambiguo o inaccesibles de este constructor .Original:T
has a direct or virtual base which has a deleted default constructor, or it is ambiguous or inaccessible from this constructor.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
T
tiene una base directa o virtual que tiene un destructor eliminado o un destructor que se puede acceder desde este constructor .Original:T
has a direct or virtual base which has a deleted destructor, or a destructor that is inaccessible from this constructor.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
T
es un miembro union con al menos una variante con constructor(desde C++11) defecto no trivial .Original:T
is a union with at least one variant member with non-trivial default constructor(desde C++11).The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
T
es un union y todos los miembros de sus variantes son const .Original:T
is a union and all of its variant members are const.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[editar] Constructor predeterminado trivial
El constructor por defecto implícitamente declarado para
T
clase es trivial si todo lo siguiente es cierto:Original:
The implicitly-declared default constructor for class
T
is trivial if all of the following is true: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
no tiene funciones miembro virtualesOriginal:T
has 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. -
T
no tiene clases base virtualesOriginal:T
has no virtual base classesThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
T
no tiene miembros no estáticos con inicializadores llave-o-igual (desde C++11)Original:T
has no non-static members with brace-or-equal initializers (desde C++11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Cada base directa de
T
tiene un constructor predeterminado trivialOriginal:Every direct base ofT
has a trivial default constructorThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Todos los miembros no estáticos de tipo de clase tiene un constructor predeterminado trivialOriginal:Every non-static member of class type has a trivial default constructorThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Un constructor predeterminado trivial es un constructor que no realiza ninguna acción. Los objetos con constructores predeterminados triviales pueden ser creadas usando reinterpret_cast en cualquier sistema de almacenamiento, por ejemplo, en la memoria asignada con std::malloc. Todos los tipos de datos compatibles con el lenguaje C (tipos POD) son trivialmente default-construible .
Original:
A trivial default constructor is a constructor that performs no action. Objects with trivial default constructors can be created by using reinterpret_cast on any storage, e.g. on memory allocated with std::malloc. All data types compatible with the C language (POD types) are trivially default-constructible.
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.
[editar] Implícitamente definido constructor predeterminado
Si el constructor predeterminado implícitamente declarada no se elimina o trivial, está definido (es decir, un cuerpo de función es generado y compilado) por el compilador, y tiene exactamente el mismo efecto que un constructor definido por el usuario con el cuerpo vacío y vacío inicializador lista. Es decir, se llama a los constructores por defecto de las bases y de los miembros no estáticos de esta clase .
Original:
If the implicitly-declared default constructor is not deleted or trivial, it is defined (that is, a function body is generated and compiled) by the compiler, and it has exactly the same effect as a user-defined constructor with empty body and empty initializer list. That is, it calls the default constructors of the bases and of the non-static members of this class.
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.
[editar] Ejemplo
struct A { int x; A(int x = 1) : x(x) {} // user-defined default ctor }; struct B : A { // B::B() is implicitly-defined, calls A::A() }; struct C { A obj; // C::C() is implicitly-defined, calls A::A() }; struct D : A { D(int y) : A(y) {} // D::D() is not declared because another constructor exists }; struct E : A { E(int y) : A(y) {} E() = default; // explicitly defaulted, calls A::A() }; struct F { int& ref; // reference member const int c; // const member // Bad::Bad() is deleted }; int main() { A a; B b; // D d; // compile error E e; // F f; // compile error }