Espacios de nombres
Variantes
Acciones

static_cast conversion

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
 
Convierte entre tipos usando una combinación de conversiones implícitas y definidas por el usuario .
Original:
Converts between types using a combination of implicit and user-defined conversions.
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

static_cast < new_type > ( expression )
Devuelve un valor de tipo new_type .
Original:
Returns a 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.

[editar] Explicación

Sólo las siguientes conversiones se puede hacer con static_cast, excepto cuando tales conversiones sería desechado constness''' o volatilidad .
Original:
Only the following conversions can be done with static_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)
Si un objeto temporal de new_type tipo se puede declarar e inicializar con expression, como por new_type Temp(expression);, que puede implicar conversiones implícitas, una llamada al constructor de new_type o una llamada a un usuario definido por el operador de conversión, entonces static_cast<type>(expression) calcula y devuelve el valor de ese objeto temporal .
Original:
If a temporary object of type new_type can be declared and initialized with expression, as by new_type Temp(expression);, which may involve implicit conversions, a call to the constructor of new_type or a call to a user-defined conversion operator, then static_cast<type>(expression) computes and returns the value of that temporary object.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Si new_type es un puntero o referencia a algunos D clase y el tipo de expression es un puntero o referencia a su no-virtual base de B, static_cast realiza una' abatido. Tal static_cast no verifica tiempo de ejecución para asegurarse de que el tipo en tiempo de ejecución del objeto es en realidad D, y sólo puede ser utilizado con seguridad si esta condición está garantizada por otros medios, como por ejemplo en la aplicación de polimorfismo estático. Safe abatido se puede hacer con dynamic_cast .
Original:
If new_type is a pointer or reference to some class D and the type of expression is a pointer or reference to its non-virtual base B, static_cast performs a downcast. Such static_cast makes no runtime checks to ensure that the object's runtime type is actually D, and may only be used safely if this precondition is guaranteed by other means, such as when implementing polimorfismo estático. Safe downcast may be done with dynamic_cast.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Si new_type es un tipo de referencia rvalue, static_cast convierte el valor de expression a' xValue. Este tipo de static_cast se utiliza para implementar la semántica de movimiento de std::move. (desde C++11)
Original:
If new_type is an rvalue reference type, static_cast converts the value of expression to xvalue. This type of static_cast is used to implement move semantics in std::move. (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.
4)
Si new_type es el tipo void (posiblemente cv-calificados), static_cast descarta el valor de expression después de su evaluación .
Original:
If new_type is the type void (possibly cv-qualified), static_cast discards the value of expression after evaluating it.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
5) new_type al tipo de expression existe, que no incluye el valor-a rvalue, array-a-puntero, la función-a-puntero, puntero nulo, puntero nulo miembro, o la conversión booleano, entonces static_cast puede realizar la inversa de la conversión implícita .
Original:
If an
conversión implícita
Original:
implicit conversion
The text has been machine-translated via [http://translate.google.com Google Translate].
You can help to correct and verify the translation. Click [http://en.cppreference.com/w/Cppreference:MachineTranslations here] for instructions.
</div>
sequence from new_type to the type of expression exists, that does not include lvalue-to-rvalue, array-to-pointer, function-to-pointer, null pointer, null member pointer, or boolean conversion, then static_cast can perform the inverse of that implicit conversion.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
6)
Si la conversión de expression a new_type implica lvalue-a-valor p, matriz de puntero-, o función a puntero de conversión, se puede realizar de forma explícita por static_cast .
Original:
If conversion of expression to new_type involves lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion, it can be performed explicitly by static_cast.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
7)
Tipo de enumeración Scoped se puede convertir en un tipo entero o de punto flotante. (desde C++11)
Original:
Scoped enumeration type can be converted to an integer or floating-point type. (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.
8)
Tipo entero, punto flotante, o enumeración se puede convertir en cualquier tipo de enumeración (el resultado es indeterminado si el valor de expression, se convirtió al tipo subyacente de la enumeración, no es uno de los valores objetivo de enumeración)
Original:
Integer, floating-point, or enumeration type can be converted to any enumeration type (the result is unspecified if the value of expression, converted to the enumeration's underlying type, is not one of the target enumeration values)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
9)
Un puntero a miembro de una clase puede ser D upcast a un puntero a miembro de su B clase base. Esta static_cast no verifica para asegurar el miembro actualmente existe en el tipo de tiempo de ejecución del objeto puntiagudo para .
Original:
A pointer to member of some class D can be upcast to a pointer to member of its base class B. This static_cast makes no checks to ensure the member actually exists in the runtime type of the pointed-to object.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
10)
Un prvalue de tipo puntero a void (posiblemente cv-cualificada) se puede convertir en puntero a cualquier tipo. La conversión de cualquier puntero a puntero a void y de vuelta al puntero a la original (o más cv-calificado) Tipo conserva su valor original .
Original:
A prvalue of type pointer to void (possibly cv-qualified) can be converted to pointer to any type. Conversion of any pointer to pointer to void and back to pointer to the original (or more cv-qualified) type preserves its original value.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Como con todas las expresiones de conversión, el resultado es:
Original:
As with all 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.
  • un valor-si new_type es un tipo de referencia o una referencia de valor-valor-poder funcionar en su tipo;
    Original:
    an lvalue if new_type is an lvalue reference type or an rvalue reference to function type;
    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 una referencia a rvalue tipo de objeto;
    Original:
    an xvalue if new_type is an rvalue reference to object type;
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • un prvalue de otra manera .
    Original:
    a prvalue otherwise.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar] Notas

static_cast también se puede utilizar para eliminar la ambigüedad de sobrecargas de función mediante la realización de una función de conversión a puntero a tipo específico, como en std::transform(s.begin(), s.end(), s.begin(), static_cast<int(*)(int)>(std::toupper));
Original:
static_cast may also be used to disambiguate function overloads by performing a function-to-pointer conversion to specific type, as in std::transform(s.begin(), s.end(), s.begin(), static_cast<int(*)(int)>(std::toupper));
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Palabras clave

static_cast

[editar] Ejemplo

#include <vector>
#include <iostream>
 
struct B {};
struct D : B {};
 
enum class E { ONE, TWO, THREE };
enum EU { ONE, TWO, THREE };
 
int main()
{
    // 1: initializing conversion
    int n = static_cast<int>(3.14); 
    std::cout << "n = " << n << '\n';
    std::vector<int> v = static_cast<std::vector<int>>(10);
    std::cout << "v.size() = " << v.size() << '\n';
 
    // 2: static downcast
    D d;
    B& br = d; // upcast via implicit conversion
    D& another_d = static_cast<D&>(br); // downcast
 
    // 3: lvalue to xvalue
    std::vector<int> v2 = static_cast<std::vector<int>&&>(v);
    std::cout << "after move, v.size() = " << v.size() << '\n';
 
    // 4: discarded-value expression
    static_cast<void>(v2.size());
 
    // 5. inverse of implicit conversion
    // todo
 
    // 6. array-to-pointer followed by upcast
    D a[10];
    B* dp = static_cast<B*>(a);
 
    // 7. scoped enum to int or float
    E e = E::ONE;
    int one = static_cast<int>(e);
 
    // 8. int to enum, enum to another enum
    E e2 = static_cast<E>(one);
    EU eu = static_cast<EU>(e2);
 
    // 9. pointer to member upcast
    // todo
 
    // 10. void* to any type
    void* voidp = &e;
    std::vector<int>* p = static_cast<std::vector<int>*>(voidp);
}

Output:

n = 3
v.size() = 10
after move, v.size() = 0

[editar] Ver también