static_cast conversion
Da 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. |
Convertidos entre os tipos usando uma combinação de conversões implícitas e definidos pelo usuário.
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.
You can help to correct and verify the translation. Click here for instructions.
Índice |
[editar] Sintaxe
static_cast < new_type > ( expression )
|
|||||||||
Retorna um valor de
new_type
tipo.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.
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 static_cast, excepto quando essas conversões seria lançado fora constness''' ou volatilidade.
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.
You can help to correct and verify the translation. Click here for instructions.
1)
Se um objeto temporário de new_type tipo pode ser declarada e inicializada com expression, como por new_type Temp(expression);, que pode envolver conversões implícitas, uma chamada para o construtor de new_type ou uma chamada para um operador definido pelo usuário conversão, então static_cast<type>(expression) calcula e retorna o valor do objeto temporário.
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.
You can help to correct and verify the translation. Click here for instructions.
2)
Se new_type é um ponteiro ou referência a alguns
D
classe e o tipo de expression é um ponteiro ou referência a sua base não-virtual B
, static_cast
executa uma' abatido. static_cast
tal, não faz verificações de tempo de execução para garantir que tipo de tempo de execução do objeto é realmente D
, e só pode ser usado com segurança se essa condição é garantida por outros meios, como na implementação polimorfismo estático. Abatida seguro pode ser feito com 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.
You can help to correct and verify the translation. Click here for instructions.
3)
Se new_type é um tipo de referência rvalue,
static_cast
converte o valor de expression para xValue. Este tipo de static_cast
é usada para implementar a semântica de se mover em 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.
You can help to correct and verify the translation. Click here for instructions.
4)
Se new_type é o tipo void (possivelmente cv qualificado),
static_cast
descarta o valor de expression depois avaliá-lo.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.
You can help to correct and verify the translation. Click here for instructions.
5) new_type com o tipo de expression existe, que não inclui lvalue-a-rvalue, array para ponteiro, função para-ponteiro, ponteiro nulo, membro ponteiro nulo, ou conversão boolean, então
static_cast
pode realizar o inverso do que a conversão implícita.Original:
If an
conversão implícita</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
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.
You can help to correct and verify the translation. Click [http://en.cppreference.com/w/Cppreference:MachineTranslations here] for instructions.
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.
You can help to correct and verify the translation. Click here for instructions.
6)
Se a conversão de expression new_type envolve lvalue para rvalue, matriz-to-ponteiro, ou uma função-para-ponteiro de conversão, pode ser realizado por explicitamente
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.
You can help to correct and verify the translation. Click here for instructions.
7)
Tipo de enumeração escopo pode ser convertido para um tipo inteiro ou de ponto flutuante. (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.
You can help to correct and verify the translation. Click here for instructions.
8)
Tipo, um número inteiro de ponto flutuante, ou enumeração pode ser convertido para qualquer tipo de enumeração (o resultado não é especificado, se o valor de expression, convertido para o tipo subjacente da enumeração, não é um dos valores de enumeração de destino)
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.
You can help to correct and verify the translation. Click here for instructions.
9)
Um ponteiro para membro de alguma
D
classe pode ser upcast para um ponteiro para membro do seu B
classe base. Este static_cast
não faz verificações para garantir o membro realmente existe no tipo de tempo de execução do objeto pontiagudo 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.
You can help to correct and verify the translation. Click here for instructions.
10)
Um ponteiro de tipo de prvalue para void (possivelmente cv qualificado) pode ser convertido para qualquer tipo de ponteiro. Conversão de qualquer ponteiro para ponteiro para anular e voltar para ponteiro para o tipo (ou mais cv qualificado) original preserva seu 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.
You can help to correct and verify the translation. Click here for instructions.
Tal como acontece com todas as expressões fundido, o resultado é:
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.
You can help to correct and verify the translation. Click here for instructions.
- um lvalue se new_type é um tipo de referência ou uma referência lvalue rvalue a funcionar 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. - um xValue se new_type é uma referência para 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. - uma outra forma prvalue.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 também pode ser utilizado para resolver a ambiguidade sobrecargas de função, realizando uma função de conversão-para-ponteiro de tipo específico, como em 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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Palavras-chave
[editar] Exemplo
#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); }
Saída:
n = 3 v.size() = 10 after move, v.size() = 0