dynamic_cast conversion
De cppreference.com
![]() |
Esta página se ha traducido por ordenador/computador/computadora de la versión en inglés de la Wiki usando Google Translate.
La traducción puede contener errores y palabras aparatosas/incorrectas. Planea sobre el texto para ver la versión original. Puedes ayudar a corregir los errores y mejorar la traducción. Para instrucciones haz clic aquí. |
Con seguridad convierte punteros y referencias a clases de arriba, abajo y hacia los lados a lo largo de la jerarquía de herencia .
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.
You can help to correct and verify the translation. Click here for instructions.
Contenido |
[editar] Sintaxis
dynamic_cast < new_type > ( expression )
|
|||||||||
Si la operación tiene éxito, dynamic_cast
devuelve un valor del tipo new_type. Si la operación falla y new_type es un puntero, se devuelve un puntero null. Si la operación falla y new_type
es una referencia, se lanza una excepción de tipo std::bad_cast.
[editar] Explicación
Sólo las siguientes conversiones se puede hacer con dynamic_cast, excepto cuando tales conversiones sería desechado constness''' o volatilidad .
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.
You can help to correct and verify the translation. Click here for instructions.
1)
Si el tipo de expression es exactamente la new_type o una versión menos cv-calificado de new_type, el resultado es 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.
You can help to correct and verify the translation. Click here for instructions.
2)
Si el valor de expression es el valor del puntero nulo, el resultado es el valor de puntero nulo de 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.
You can help to correct and verify the translation. Click here for instructions.
3)
Si new_type es un puntero o referencia a
Base
, y el tipo de expression es un puntero o referencia a Derived
, donde Base
es una clase única, base accesible de Derived
, el resultado es un puntero o una referencia a la clase subobjeto Base
dentro de la Derived
objeto puntiagudo o identificado por expression. (Nota: La conversión implícita y static_cast puede realizar esta conversión también)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.
You can help to correct and verify the translation. Click here for instructions.
4)
Si expression es un puntero o una referencia a un tipo polimórfico, y
new_type
es un puntero a void, el resultado es un puntero a la mayoría de los derivados objeto puntiagudo o referenciado 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.
You can help to correct and verify the translation. Click here for instructions.
5)
Si expression es un puntero o referencia a un tipo polimórfico
Base
y new_type
es un puntero o una referencia al tipo Derived
una comprobación en tiempo de ejecución que se realizaOriginal:
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.
You can help to correct and verify the translation. Click here for instructions.
a)
El objeto más derivado extendidos / identificado por expression se examina. Si, en ese objeto, los puntos expression / es referida a una base pública de
Derived
, y si sólo una subobjeto de tipo Derived
se deriva del subobjeto señaló / identificado por expression, entonces el resultado de los puntos de reparto / subobjeto que se refiere a Derived
. (Esto se conoce como la "abatido")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.
You can help to correct and verify the translation. Click here for instructions.
b)
De lo contrario, si los puntos de expression / refiere a una base pública del objeto más derivada, y, simultaneamente, la mayoría de los derivados objeto tiene una clase base pública inequívoca de
Derived
tipo, el resultado de los puntos de reparto / refiere a que Derived
(esto se conoce como la "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.
You can help to correct and verify the translation. Click here for instructions.
c)
De lo contrario, el tiempo de ejecución de verificación falla. Si el dynamic_cast se utiliza en punteros, el valor de puntero nulo new_type tipo se devuelve. Si se ha utilizado en las referencias, el std::bad_cast excepción .
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.
You can help to correct and verify the translation. Click here for instructions.
6)
Cuando dynamic_cast se utiliza en un constructor o un destructor (directa o indirectamente), y expression se refiere al objeto que está actualmente en construcción / destrucción, el objeto se considera que es el objeto más derivada. Si new_type no es un puntero o referencia a / destructor de la clase propia de la construcción o de una de sus bases, el comportamiento no está definido .
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.
You can help to correct and verify the translation. Click here for instructions.
Similar a otras expresiones de conversión, el resultado es:
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.
You can help to correct and verify the translation. Click here for instructions.
- un valor-si new_type es un tipo de valor-referencia (expression debe ser un valor-I)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. - un xValue si new_type es un tipo de referencia rvalue (expression puede ser lvalue o 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. - un prvalue lo contrario (en este caso, si new_type es un tipo de puntero)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 también se puede realizar con static_cast, lo que evita el coste de la comprobación de tiempo de ejecución, pero sólo es seguro si el programa puede garantizar, a través de alguna otra lógica, que el objeto apuntado por expression es 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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Palabras clave
[editar] Ejemplo
Ejecuta este código
#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; }
Salida:
downcast from b2 to d successful