Espaços nominais
Variantes
Acções

dynamic_cast conversion

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.
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
 
Segurança converte ponteiros e referências a classes cima, para baixo e para os lados ao longo da hierarquia de herança.
Original:
Safely converts pointers and references to classes up, down, and sideways along the inheritance hierarchy.
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

dynamic_cast < new_type > ( expression )
Retorna um valor de new_type tipo ou lança uma exceção.
Original:
Returns a value of type new_type or throws an exception.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Explicação

Apenas as seguintes conversões podem ser feitas com dynamic_cast, excepto quando essas conversões seria lançado fora constness''' ou volatilidade.
Original:
Only the following conversions can be done with dynamic_cast, except when such conversions would cast away constness or volatility.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
1)
Se o tipo de expression é o new_type exactamente ou uma versão menos cv qualificado de new_type, o resultado é expression.
Original:
If the type of expression is the exactly new_type or a less cv-qualified version of new_type, the result is expression.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Se o valor de expression é o valor de ponteiro nulo, o resultado é o valor de ponteiro nulo new_type tipo
Original:
If the value of expression is the null pointer value, the result is the null pointer value of type new_type
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Se new_type é um ponteiro ou referência a Base, e do tipo de expression é um ponteiro ou referência a Derived, onde Base é único, classe de base de Derived acessível, o resultado é um ponteiro ou referência da classe subobject Base dentro do Derived objeto apontado ou identificados pela expression. (Nota: conversão implícita e static_cast pode realizar essa conversão também)
Original:
If new_type is a pointer or reference to Base, and the type of expression is a pointer or reference to Derived, where Base is a unique, accessible base class of Derived, the result is a pointer or reference to the Base class subobject within the Derived object pointed or identified by expression. (note: implicit cast and static_cast can perform this conversion as well)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
4)
Se expression é um ponteiro ou referência a um tipo polimórfico, e new_type é um ponteiro para void, o resultado é um ponteiro para o objeto mais derivada apontou ou referenciada por expression.
Original:
If expression is a pointer or reference to a polymorphic type, and new_type is a pointer to void, the result is a pointer to the most derived object pointed or referenced by expression.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
5)
Se expression é um ponteiro ou referência a um Base tipo polimórfico, e new_type é um ponteiro ou referência para o tipo Derived uma verificação em tempo de execução é realizado:
Original:
If expression is a pointer or reference to a polymorphic type Base, and new_type is a pointer or reference to the type Derived a run-time check is performed:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
a)
O objeto mais derivada apontado / identificado por expression é examinado. Se, nesse objecto, pontos expression / referes ao público de uma base Derived, e se apenas um tipo de subobject Derived é derivado do subobject apontou / identificado por expression, então o resultado dos pontos de fundição / refere-se a que subobject Derived. (Isto é conhecido como a "downcast")
Original:
The most derived object pointed/identified by expression is examined. If, in that object, expression points/referes to a public base of Derived, and if only one subobject of Derived type is derived from the subobject pointed/identified by expression, then the result of the cast points/refers to that Derived subobject. (this is known as the "downcast")
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
b)
Caso contrário, se os pontos de expression / refere-se a uma base de público do objeto mais derivado, e, de forma simultânea, o objecto mais derivada tem uma classe base inequívoca público de Derived tipo, o resultado dos pontos de fundição / refere-se a que Derived (isto é conhecido como o "sidecast")
Original:
Otherwise, if expression points/refers to a public base of the most derived object, and, simultanously, the most derived object has an unambiguous public base class of type Derived, the result of the cast points/refers to that Derived (this is known as the "sidecast")
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
c)
Caso contrário, o tempo de execução de verificação falha. Se o dynamic_cast é usado em ponteiros, o valor do ponteiro nulo do tipo new_type é devolvido. Se ele foi usado em referências, o std::bad_cast exceção é lançada.
Original:
Otherwise, the runtime check fails. If the dynamic_cast is used on pointers, the null pointer value of type new_type is returned. If it was used on references, the exception std::bad_cast is thrown.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
6)
Quando dynamic_cast é usado em um construtor ou um destrutor (direta ou indiretamente), e expression se refere ao objeto que está atualmente em fase de construção / destruição, o objeto é considerado o objeto mais derivada. Se new_type não é um ponteiro ou referência para a construção da classe / destruidor do próprio ou uma de suas bases, o comportamento é indefinido.
Original:
When dynamic_cast is used in a constructor or a destructor (directly or indirectly), and expression refers to the object that's currently under construction/destruction, the object is considered to be the most derived object. If new_type is not a pointer or reference to the construction's/destructor's own class or one of its bases, the behavior is undefined.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Semelhantes às expressões elenco, o resultado é:
Original:
Similar to other cast expressions, the result is:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • um lvalue se new_type é um lvalue tipo de referência (expression deve ser um lvalue)
    Original:
    an lvalue if new_type is an lvalue reference type (expression must be an lvalue)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • um xValue se new_type é um tipo de referência rvalue (expression pode ser lvalue ou rvalue)
    Original:
    an xvalue if new_type is an rvalue reference type (expression may be lvalue or rvalue)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • uma outra forma prvalue (neste caso, se new_type é um tipo de ponteiro)
    Original:
    a prvalue otherwise (in this case, if new_type is a pointer type)
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar] Nota

Abatido também pode ser realizada com static_cast, o que evita o custo do cheque de tempo de execução, mas é apenas seguro se o programa pode garantir, através de alguma outra lógica, que o objeto apontado por expression é definitivamente Derived.
Original:
Downcast can also be performed with static_cast, which avoids the cost of the runtime check, but it's only safe if the program can guarantee, through some other logic, that the object pointed to by expression is definitely Derived.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Palavras-chave

dynamic_cast

[editar] Exemplo

#include <iostream>
 
struct V {
    virtual void f() {};  // must be polymorphic to use runtime-checked dynamic_cast
};
struct A : virtual V {};
struct B : virtual V {
  B(V* v, A* a) {
    // casts during construction
    dynamic_cast<B*>(v); // well-defined: v of type V*, V base of B, results in B*
    dynamic_cast<B*>(a); // undefined behavior: a has type A*, A not a base of B
  }
};
struct D : A, B {
    D() : B((A*)this, this) { }
};
 
struct Base {
    virtual ~Base() {}
};
 
struct Derived: Base {
    virtual void name() {}
};
 
int main()
{
    D d; // the most derived object
    A& a = d; // upcast, dynamic_cast may be used, but unnecessary
    D& new_d = dynamic_cast<D&>(a); // downcast
    B& new_b = dynamic_cast<B&>(a); // sidecast
 
 
    Base* b1 = new Base;
    if(Derived* d = dynamic_cast<Derived*>(b1))
    {
        std::cout << "downcast from b1 to d successful\n";
        d->name(); // safe to call
    }
 
    Base* b2 = new Derived;
    if(Derived* d = dynamic_cast<Derived*>(b2))
    {
        std::cout << "downcast from b2 to d successful\n";
        d->name(); // safe to call
    }
 
    delete b1;
    delete b2;
}

Output:

downcast from b2 to d successful

[editar] Veja também