Espaços nominais
Variantes
Acções

Default constructors

Da cppreference.com
< cpp‎ | language

 
 
Linguagem C + +
Tópicos gerais
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.
Controle de fluxo
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.
Declarações execução condicional
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.
Instruções de iteração
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 declarações
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.
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaração da função
lambda declaração da função
modelo de função
linha especificador
especificações de exceção (obsoleta)
noexcept especificador (C++11)
Exceções
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Namespaces
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)
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
armazenamento duração especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialização
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Literais
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expressões
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representações alternativas
Utilitários
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
tipo de alias declaração (C++11)
atributos (C++11)
Lança
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversões implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
Elenco C-estilo e funcional
Alocação de memória
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.
Classes
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classe propriedades específicas de função
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.
Funções membro especiais
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.
construtor padrão
copiar construtor
mover construtor (C++11)
Modelos
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
modelo de classe
modelo de função
especialização de modelo
pacotes de parâmetros (C++11)
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Assembly embutido
 
Um construtor padrão é um construtor que pode ser chamado sem argumentos (ou definidos com uma lista de parâmetros vazia, ou com argumentos padrão fornecidos para cada parâmetro). Um tipo com um construtor público padrão é 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.

Índice

[editar] Sintaxe

ClassName ( ) ; (1)
ClassName :: ClassName ( ) body (2)
ClassName() = delete ; (3) (a partir do C++ 11)
ClassName() = default ; (4) (a partir do C++ 11)

[editar] Explicação

1)
Declaração de um construtor padrão
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.
2)
Definição do construtor fora do corpo da classe
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.
3)
Inibindo a geração automática de um construtor padrão
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.
4)
Explicitamente forçar a geração automática de um construtor padrão
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.
ClassName é o identificador da classe de inclusão
Original:
ClassName is the identifier of the enclosing class
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Os construtores padrão são chamados quando:
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.
  • criação de objetos ou matrizes de duração estática de armazenamento, de segmento local, e automático que são declarados sem um inicializador, (T obj; ou 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.
  • criação de objetos do tempo de armazenamento dinâmico quando a nova expressão é escrito sem um 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.
  • criação de matrizes de duração de armazenamento dinâmico com o new T[n] expressão
    Original:
    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.
  • criação de valor-inicializados objetos temporários com a expressão de conversão 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] Implicitamente declarou construtor padrão

Se nenhum construtor definidas pelo usuário de qualquer espécie são fornecidos para um tipo de classe (struct, class, ou union), o compilador sempre declarar um construtor padrão como membro inline public de sua classe. Se alguns construtores definidos pelo usuário estão presentes, o usuário pode ainda forçar a geração do construtor implicitamente declarado com a palavra-chave default (a partir do 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 (a partir do C++ 11).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Excluídos construtor padrão implicitamente declarado

O construtor padrão implicitamente declarado ou inadimplente para T classe é (até C + 11) indefinido / definido como excluídos (a partir do C++ 11) se qualquer uma das seguintes situações:
Original:
The implicitly-declared or defaulted default constructor for class T is undefined (até C + 11) / defined as deleted (a partir do 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.
  • T tem um membro do tipo de referência (sem uma cinta-ou-igual initializer(a partir do C++ 11)).
    Original:
    T has a member of reference type (without a brace-or-equal initializer(a partir do 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 tem um membro const (sem initializer(a partir do C++ 11) cinta-ou-igual) ou definido pelo usuário construtor padrão.
    Original:
    T has a const member (without a brace-or-equal initializer(a partir do 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 tem um membro (sem initializer(a partir do C++ 11) cinta-ou-igual), que tem um construtor padrão excluído, ou seu construtor padrão é ambíguo ou inacessível a partir deste construtor.
    Original:
    T has a member (without a brace-or-equal initializer(a partir do 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 tem uma base direta ou virtual que tem um construtor padrão excluído, ou é ambíguo ou inacessível a partir deste construtor.
    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 tem uma base direta ou virtual que tem um destrutor excluído, ou um destruidor que é inacessível a partir deste construtor.
    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 é um union com pelo menos um membro com a variante não-trivial constructor(a partir do C++ 11) padrão.
    Original:
    T is a union with at least one variant member with non-trivial default constructor(a partir do 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 é um union e todas as suas variantes são membros 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] Construtor padrão trivial

O construtor padrão implicitamente declarado para T classe é trivial se todo o seguinte é verdadeiro:
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.
  • T não tem funções de membro virtual
    Original:
    T has 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.
  • T não tem classes base virtuais
    Original:
    T has no virtual base classes
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • T não possui membros não-estáticos com inicializadores de cinta-ou-iguais (a partir do C++ 11)
    Original:
    T has no non-static members with brace-or-equal initializers (a partir do 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 direta de T tem um construtor padrão trivial
    Original:
    Every direct base of T has a trivial default constructor
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Cada membro não-estático do tipo classe tem um construtor padrão trivial
    Original:
    Every non-static member of class type has a trivial default constructor
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Um construtor padrão trivial é um construtor que não executa nenhuma ação. Objetos com construtores padrão triviais podem ser criados usando reinterpret_cast em qualquer armazenamento, por exemplo, em memória alocada com std::malloc. Todos os tipos de dados compatíveis com a linguagem C (tipos POD) são trivialmente padrão-constructible.
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.

[editar] Implicitamente definido construtor padrão

Se o construtor padrão implicitamente declarado não é excluído ou trivial, é definido (isto é, um corpo de função é gerado e compilado) pelo compilador, e ele tem exatamente o mesmo efeito que um construtor definido pelo usuário com o corpo vazio e vazio lista de inicializador. Ou seja, ele chama os construtores padrão das bases e dos membros não-estáticos desta classe.
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.

[editar] Exemplo

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
}