Пространства имён
Варианты
Действия

explicit type conversion

Материал из cppreference.com

 
 
Язык С++
Общие темы
Управление программой
Операторы условного выполнения
Операторы повторения
Операторы перехода
Функции
объявление функции
объявление лямбда-функции
шаблон функции
спецификатор inline
спецификаторы исключений (устарело)
спецификатор noexcept (C++11)
Исключения
Пространства имён
объявление пространства имён
псевдонимы пространства имён
Типы
спецификатор decltype (C++11)
Спецификаторы
cv-спецификаторы
спецификаторы продолжительности хранения
спецификатор constexpr (C++11)
спецификатор auto (C++11)
спецификатор alignas (C++11)
Инициализация
Литералы
Выражения
Утилиты
Типы
typedef-объявление
объявление псевдонима типа (C++11)
атрибуты (C++11)
Приведения типов
неявные преобразования
const_cast-преобразование
static_cast-преобразование
dynamic_cast-преобразование
reinterpret_cast-преобразование
C-подобное и функциональное приведение типов
Выделение памяти
Классы
Особые свойства классовых функций
Специальные функции-члены
Шаблоны
шаблон класса
шаблон функции
специализация шаблона
упакованные параметры (C++11)
Разное
Ассемблерные вставки
 
Преобразование между типами с использованием комбинации явных и неявных преобразований.
Original:
Converts between types using a combination of explicit and implicit conversions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[править] Синтаксис

( new_type ) expression (1)
new_type ( expression ) (2)
Возвращает значение типа 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.

[править] Объяснение

1)
Когда C-стиле литые выражение встречается, компилятор пытается следующие выражения актеров, в следующем порядке:
Original:
When the C-style cast expression is encountered, the compiler attempts the following cast expressions, in this order:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
a) const_cast<new_type>(expression)
b)
static_cast<new_type>(expression), со следующими расширениями: указатель или ссылку на производный класс, дополнительно разрешено быть приведен к указателю или ссылки на однозначный базового класса (и наоборот), даже если базовый класс недоступен (то есть, это приведение игнорирует частного наследования спецификатор). То же относится и к литья указатель на член Указатель на член unambigous не виртуальные базы
Original:
static_cast<new_type>(expression), with extensions: pointer or reference to a derived class is additionally allowed to be cast to pointer or reference to unambiguous base class (and vice versa) even if the base class is inaccessible (that is, this cast ignores the private inheritance specifier). Same applies to casting pointer to member to pointer to member of unambigous non-virtual base
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
c)
static_cast (с расширениями), а затем const_cast
Original:
static_cast (with extensions) followed by const_cast
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
d) reinterpret_cast<new_type>(expression)
e)
reinterpret_cast следует const_cast
Original:
reinterpret_cast followed by const_cast
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
@ @ Первый выбор, который удовлетворяет требованиям соответствующего оператора приведения выбран, даже если он не может быть скомпилирована (см. пример).
Original:
@@ The first choice that satisfies the requirements of the respective cast operator is selected, even if it cannot be compiled (see example).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
@ @ Кроме того, C-стиле литые обозначения допускается подавать от, до, так и между указателями на неполный тип класса. Если оба expression и new_type являются указателями на неполные типы класса, это неопределенное ли static_cast или reinterpret_cast получает выбранные.
Original:
@@ In addition, C-style cast notation is allowed to cast from, to, and between pointers to incomplete class type. If both expression and new_type are pointers to incomplete class types, it's unspecified whether static_cast or reinterpret_cast gets selected.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Функциональные литых состоит из простой спецификатор типа или ЬурейеЕ спецификатор (другими словами, одним словом имя типа: unsigned int(expression) или int*(expression) не действительны), а затем одно выражение в круглых скобках. Это литье в точности эквивалентен соответствующему C-стиле литые выражения.
Original:
The functional cast consists of a simple type specifier or a typedef specifier (in other words, a single-word type name: unsigned int(expression) or int*(expression) are not valid), followed by a single expression in parentheses. This cast is exactly equivalent to the corresponding C-style cast expression.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Как и во всех литых выражения, результат
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.
  • именующее если new_type является тип именующее ссылку или RValue ссылка на функцию типа
    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.
  • xvalue если new_type является RValue ссылку на объект типа
    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.
  • 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.

[править] Пример

double f = 3.14;
unsigned int n1 = (unsigned int)f; // C-style cast
unsigned int n2 = unsigned(f);     // functional cast
 
class C1;
class C2;
C2* foo(C1* p)
{
    return (C2*)p; // casts incomplete type to incomplete type
}
 
// In this example, C-style cast is interpreted as static_cast
// even though it would work as reinterpret_cast
struct A {};
struct I1 : A {};
struct I2 : A {};
struct D : I1, I2 {};
 
int main()
{
   D* d = nullptr;
   A* a = (A*)d;                   // compile-time error
   A* a = reinterpret_cast<A*>(d); // this compiles
}