Implicit conversions
Материал из 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. |
Неявные преобразования выполняются всякий раз, когда выражение некоторого типа
T1 используется в контексте, который не принимает этого типа, но принимает некоторые другие T2 типа, в частности:Original:
Implicit conversions are performed whenever an expression of some type
T1 is used in context that does not accept that type, but accepts some other type T2, in particular: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.
- Когда выражение используется в качестве аргумента при вызове функции, которая объявлена с
T2в качестве параметра.Original:When the expression is used as the argument when calling a function that is declared withT2as parameter.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Когда выражение используется в качестве операнда с оператором, который ожидает
T2Original:When the expression is used as an operand with an operator that expectsT2The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - При инициализации нового объекта типа
T2, в том числеreturnзаявление, в функции, возвращающейT2.Original:When initializing a new object of typeT2, includingreturnstatement in a function returningT2.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Когда выражение используется в
switchзаявление (T2является неотъемлемой частью типа)Original:When the expression is used in aswitchstatement (T2is integral type)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Когда выражение используется в
ifзаявление или петли (T2является bool)Original:When the expression is used in anifstatement or a loop (T2is bool)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Программа имеет хорошо сформированные (компилирует), только если существует один однозначный неявное преобразование последовательности из
T1 в T2. Original:
The program is well-formed (compiles) only if there exists one unambiguous implicit conversion sequence from
T1 to T2. 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.
При наличии нескольких перегрузок функции или оператора вызова, после того, как неявная последовательность преобразования построено от T1 до T2 доступны каждому, Разрешение перегрузки правил решить, какие перегрузки составлен.
Original:
If there are multiple overloads of the function or operator being called, after the implicit conversion sequence is built from T1 to each available T2, Разрешение перегрузки rules decide which overload is compiled.
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.
Содержание |
[править] Орден преобразований
Неявные преобразования последовательности состоит из следующих, в следующем порядке:
Original:
Implicit conversion sequence consists of the following, 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.
You can help to correct and verify the translation. Click here for instructions.
1)
ноль или один' стандартная последовательность преобразования
Original:
zero or one standard conversion sequence
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)
ноль или один пользовательского преобразования
Original:
zero or one user-defined 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.
3)
ноль или один стандартную последовательность преобразования
Original:
zero or one standard conversion sequence
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.
При рассмотрении аргумента конструктора или определяемые пользователем функции преобразования, только одна стандартная последовательность преобразование разрешено (в противном случае пользовательские преобразования могут быть эффективно прикован). При переходе от одного встроенного типа в другой встроенного типа, только одна стандартная последовательность преобразование разрешено.
Original:
When considering the argument to a constructor or to a user-defined conversion function, only one standard conversion sequence is allowed (otherwise user-defined conversions could be effectively chained). When converting from one built-in type to another built-in type, only one standard conversion sequence is allowed.
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.
Стандартная последовательность преобразования состоит из следующих, в следующем порядке:
Original:
A standard conversion sequence consists of the following, 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.
You can help to correct and verify the translation. Click here for instructions.
1)
ноль или один' именующее преобразований
Original:
zero or one lvalue transformation
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)
ноль или один цифровой продвижение или' числовые преобразования
Original:
zero or one numeric promotion or numeric 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.
3)
ноль или один' квалификации регулировки
Original:
zero or one qualification adjustment
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.
Пользовательского преобразования состоит из:
Original:
A user-defined conversion consists of:
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.
@ * @ Нуль или один не явный одним аргументом конструктора или не явного преобразования вызова функции
Original:
@*@ zero or one non-explicit single-argument constructor or non-explicit conversion function call
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.
Выражение
e называется неявно преобразуются в T2 тогда и только тогда декларацию T2 t=e; хорошо сформирован (может быть скомпилирована), для некоторых придумали временные t. Обратите внимание, что это отличается от T2 t(e), где явные конструкторы и функции преобразования будет дополнительно рассматриваться.Original:
An expression
e is said to be implicitly convertible to T2 if and only if the declaration T2 t=e; is well-formed (can be compiled), for some invented temporary t. Note that this is different from T2 t(e), where explicit constructors and conversion functions would additionally be considered.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++11), где тип bool ожидается
Original:
One exception is the above rule is the special implicit conversion invoked in the following five contexts (начиная с C++11), where type bool is expected:
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.
- управление выражение
if,while,forOriginal:controlling expression ofif,while,forThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - логические операторы
!,&&и||Original:the logical operators!,&&and||The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - условная
?:оператораOriginal:the conditional operator?:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
static_assert -
noexcept
-
В таких условиях, неявные преобразования последовательности построен, если декларация bool t(e); хорошо сформированы. то есть явным определяемые пользователем функции преобразования, такие как
explicit T::operator bool() const; считается. Такие e выражение называется контекстуально, конвертируемых в BOOL.Original:
in such contexts, implicit conversion sequence is built if the declaration bool t(e); is well-formed. that is, the explicit user-defined conversion function such as
explicit T::operator bool() const; is considered. Such expression e is said to be contextually convertible to bool.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.
[править] Lvalue преобразований
Lvalue преобразования применяются при именующее аргументов (например, ссылка на объект) используется в контексте, где RValue (например, числа) ожидается.
Original:
Lvalue transformations are applied when lvalue argument (e.g. reference to an object) is used in context where rvalue (e.g. a number) is expected.
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.
[править] Lvalue в RValue преобразования
Glvalue любого не-функцию, не тип массива
T может быть неявно преобразован в prvalue того же типа. Если T не является классом, это преобразование также удаляет CV-квалификаторы. Если встречаются в невычисленного контексте (в операнд SizeOf, TypeId, noexcept, или decltype), это преобразование эффективно копирование создает временный объект типа T с использованием оригинальных glvalue в качестве аргумента конструктора, и что временный объект возвращается в виде prvalue. Если glvalue имеет тип std::nullptr_t, в результате prvalue является нулевым указателем постоянной nullptr.Original:
A glvalue of any non-function, non-array type
T can be implicitly converted to prvalue of the same type. If T is a non-class type, this conversion also removes cv-qualifiers. Unless encountered in unevaluated context (in an operand of sizeof, typeid, noexcept, or decltype), this conversion effectively copy-constructs a temporary object of type T using the original glvalue as the constructor argument, and that temporary object is returned as a prvalue. If the glvalue has the type std::nullptr_t, the resulting prvalue is the null pointer constant nullptr.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.
[править] Массив для преобразования указателей
Именующее или RValue типа "массив
N T" или "массив неизвестного границу T" может быть неявно преобразован в prvalue типа "указатель на T". В результате указатель ссылается на первый элемент массива.Original:
A lvalue or rvalue of type "array of
N T" or "array of unknown bound of T" can be implicitly converted to a prvalue of type "pointer to T". The resulting pointer refers to the first element of the array.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.
[править] Функция указатель
Именующее функции
T типа может быть неявно преобразован в prvalue указатель на эту функцию. Это не относится к не-статические функции-члены, потому что lvalues, которые относятся к не-статические функции-члены не существует.Original:
An lvalue of function type
T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.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.
[править] Числовые акциях
[править] Интегральное продвижение по службе
Prvalues малых целых типов (например, char) могут быть преобразованы в prvalues больших интегральных типов (например, int). В частности, арифметических операторов не принимаю типов меньше, чем int в качестве аргументов, и интегральные акции автоматически применяются. Это преобразование всегда сохраняет значение.
Original:
Prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, арифметических операторов do not accept types smaller than int as arguments, and integral promotions are automatically applied. This conversion always preserves the 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.
Следующие неявные преобразования классифицируются как неотъемлемой акциях
Original:
The following implicit conversions are classified as integral promotions:
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.
signed charилиsigned shortмогут быть преобразованы в int.Original:signed charorsigned shortcan be converted to int.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
unsigned charилиunsigned shortмогут быть преобразованы в unsigned int.Original:unsigned charorunsigned shortcan be converted to unsigned int.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
charмогут быть преобразованы в int или unsigned int в зависимости от базового типа: signed char или unsigned char (см. выше)Original:charcan be converted to int or unsigned int depending on the underlying type: signed char or unsigned char (see above)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
wchar_t,char16_t, иchar32_tможет быть преобразован в первый тип из списка в состоянии провести весь свой диапазон значений: int, unsigned int, long, unsigned long, long long, unsigned long long.Original:wchar_t,char16_t, andchar32_tcan be converted to the first type from the following list able to hold their entire value range: int, unsigned int, long, unsigned long, long long, unsigned long long.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- ' Незаданной перечисления типа, базовый тип не зафиксировано может быть преобразован в первый тип из списка в состоянии провести весь свой диапазон значений: int, unsigned int, long, unsigned long, long long, или unsigned long long. Если значение диапазона больше не применяются интегральные акциях.Original:An unscoped enumeration type whose underlying type is not fixed can be converted to the first type from the following list able to hold their entire value range: int, unsigned int, long, unsigned long, long long, or unsigned long long. If the value range is greater, no integral promotions apply.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- ' Незаданной перечисления типа, базовый тип фиксируется могут быть преобразованы в своем способствовало базового типа. (начиная с C++11)Original:An unscoped enumeration type whose underlying type is fixed can be converted to its promoted underlying type. (начиная с C++11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Типа' битовые поля могут быть преобразованы в int, если он может представлять весь диапазон значения битовых полей, в противном случае unsigned int, если он может представлять весь диапазон значения битовых полей, в противном случае интеграл акциях применять.Original:A bitfield type can be converted to int if it can represent entire value range of the bitfield, otherwise to unsigned int if it can represent entire value range of the bitfield, otherwise no integral promotions apply.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Тип bool могут быть преобразованы в int со значением false становится 0 и true становится 1.Original:The type bool can be converted to int with the value false becoming 0 and true becoming 1.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
[править] С плавающей точкой продвижения по службе
Prvalue типа float могут быть преобразованы в prvalue типа double. Значение не меняется.
Original:
A prvalue of type float can be converted to prvalue of type double. The value does not change.
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.
[править] Числовые преобразования
В отличие от акций, числовые преобразования могут изменять значения, с потенциальной потерей точности.
Original:
Unlike the promotions, numeric conversions may change the values, with potential loss of precision.
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.
[править] Интегральных преобразований
Prvalue целого типа или незаданной типа перечисления может быть преобразовано в любое другое целое число типа. Если преобразования, перечисленные в интегральной акции, это поощрение, а не превращение.
Original:
A prvalue of an integer type or of an unscoped enumeration type can be converted to any other integer type. If the conversion is listed under integral promotions, it is a promotion and not a 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.
- Если целевой тип без знака, полученное значение является значением по модулю 2n
где n это количество бит, используемых для представления конечного типа. В дополнение арифметическое 2 в (используется на всех платформах, где C + + компиляторов имеются), это преобразование не-оп, за исключением усечение, если пункт назначения типа является маленький.Original:If the destination type is unsigned, the resulting value is the value modulo 2n
where n is the number of bits used to represent the destination type. In 2's complement arithmetic (used on all platforms where C++ compilers are available), this conversion is a no-op, except for the truncation if the destination type is to small.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Если целевой тип подписан, значение не изменяется, если источник число может быть представлено в пункт назначения типа. В противном случае результат зависит от реализации.Original:If the destination type is signed, the value does not change if the source integer can be represented in the destination type. Otherwise the result is implementation-defined.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Если исходный тип bool, значение false превращается в нуль, а значение true преобразуется в значение одного из назначения типа (обратите внимание, что если пункт назначения типа int, это целое продвижение по службе, не является целым числом преобразования)Original:If the source type is bool, the value false is converted to zero and the value true is converted to the value one of the destination type (note that if the destination type is int, this is an integer promotion, not an integer conversion)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Если целевой тип bool, это логическое преобразование (см. ниже)Original:If the destination type is bool, this is a boolean conversion (see below)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
[править] С плавающей точкой преобразования
Prvalue из типа с плавающей точкой могут быть преобразованы в prvalue любого другого типа с плавающей точкой. Если преобразования, перечисленные в с плавающей точкой акциях, это поощрение, а не превращение.
Original:
A prvalue of an floating-point type can be converted to prvalue of any other floating-point type. If the conversion is listed under floating-point promotions, it is a promotion and not a 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.
- Если исходное значение может быть представлено точно в пункт назначения типа, это не меняет.Original:If the source value can be represented exactly in the destination type, it does not change.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Если исходное значение находится между двумя представимых значений конечного типа, то результат будет один из этих двух значений (она определяется реализацией которого один)Original:If the source value is between two representable values of the destination type, the result is one of those two values (it is implementation-defined which one)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- В противном случае, поведение не определено.Original:Otherwise, 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.
-
[править] Плавающая - неотъемлемая преобразований
- Prvalue с плавающей точкой типа могут быть преобразованы в prvalue любого целого типа. Дробная часть обрезается, то есть дробная часть отбрасывается. Если значение не может вписаться в целевой тип, поведение не определено. Если целевой тип bool, это логическое преобразование (см. ниже).Original:A prvalue of floating-point type can be converted to prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded. If the value can not fit into the destination type, the behavior is undefined. If the destination type is bool, this is a boolean conversion (see below).The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Prvalue целых или незаданной типа перечисления может быть преобразован в prvalue любого типа с плавающей точкой. Если значение не может быть представлена правильно, это реализация определена ли ближайшая выше или ниже ближайшего представимо значение будет выбрано. Если значение не может вписаться в целевой тип, поведение не определено. Если исходный тип bool, значение false превращается в нуль, а значение true превращается в один.Original:A prvalue of integer or unscoped enumeration type can be converted to prvalue of any floating-point type. If the value can not be represented correctly, it is implementation defined whether the closest higher or the closest lower representable value will be selected. If the value can not fit into the destination type, the behavior is undefined. If the source type is bool, the value false is converted to zero, and the value true is converted to one.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
[править] Указатель преобразования
- Указатель' нулевой постоянной NULL или любой другой prvalue интегрального типа, который оценивается в ноль или любое prvalue типа std::nullptr_t, в том числе указатель' нулевые буквальном nullptr, могут быть преобразованы в любой тип указателя, и в результате нулевое значение указателя этого типа. Такое преобразование (известный как "нулевые преобразования указателей допускается преобразования малыш резюме квалифицированных типа как единого преобразования, то есть, это не считается сочетание цифровой и квалификационные преобразования).Original:The null pointer constant NULL or any other prvalue of integral type that evaluates to zero or any prvalue of type std::nullptr_t, including the null pointer literal nullptr, can be converted to any pointer type, and the result is the null pointer value of that type. Such conversion (known as 'null pointer conversion is allowed to conver tot a cv-qualified type as a single conversion, that is, it's not considered a combination of numeric and qualifying conversions).The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Prvalue указатель на любой (необязательно резюме квалифицированных) объекта
Tтипа может быть преобразован в указатель на prvalue (тождественно резюме квалифицированных) void. ЕслиTне фактический тип, то к объекту, в результате указатель доводят до указывают на начало хранения занимают наиболее объект, производный. Если исходный указатель является нулевое значение указателя, в результате нулевое значение указателя назначения типа.Original:A prvalue pointer to any (optionally cv-qualified) object typeTcan be converted to a prvalue pointer to (identically cv-qualified) void. IfTis not the runtime type of the pointed-to object, the resulting pointer is adjusted to point to the start of the storage occupied by the most-derived object. If the original pointer is a null pointer value, the result is a null pointer value of the destination type.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Prvalue указатель (опционально резюме квалифицированных) тип производного класса может быть преобразован в prvalue указатель на его доступным, однозначные (тождественно резюме квалифицированных) базового класса. Результатом преобразования является указателем на подобъектов базового класса в пределах, то к объекту. Нулевое значение указателя превращается в нулевое значение указателя назначения типа.Original:A prvalue pointer to a (optionally cv-qualified) derived class type can be converted to prvalue pointer to its accessible, unambiguous (identically cv-qualified) base class. The result of the conversion is a pointer to the base class subobject within the pointed-to object. The null pointer value is converted to the null pointer value of the destination type.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
[править] Указатель на член преобразований
- Указатель' нулевой постоянной NULL или любой другой prvalue интегрального типа, который оценивается в ноль или любое prvalue типа std::nullptr_t, в том числе указатель' нулевые буквальном nullptr, могут быть преобразованы в любой указатель на тип элемента, и в результате нулевое значение указателя этого типа. Такое преобразование (известный как "нулевые преобразования указателей допускается преобразования малыш резюме квалифицированных типа как единого преобразования, то есть, это не считается сочетание цифровой и квалификационные преобразования).Original:The null pointer constant NULL or any other prvalue of integral type that evaluates to zero or any prvalue of type std::nullptr_t, including the null pointer literal nullptr, can be converted to any pointer-to-member type, and the result is the null pointer value of that type. Such conversion (known as 'null pointer conversion is allowed to conver tot a cv-qualified type as a single conversion, that is, it's not considered a combination of numeric and qualifying conversions).The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Prvalue указатель на член того или иного типа
TвBбазовый класс может быть преобразован в prvalue указатель на член того же типаTв его производныхDкласса. ЕслиBнедоступна, неоднозначный, или виртуальную базуDили является базой некоторой промежуточной виртуальной базыD, преобразования плохо сформированные (не компилируется). В результате указателя может быть разыменован сDобъект, и он будет иметь доступ членов в подобъектаBбазы, чтоDобъекта. Нулевое значение указателя превращается в нулевое значение указателя назначения типа.Original:Prvalue pointer to member of some typeTin a base classBcan be converted to prvalue pointer to member of the same typeTin its derived classD. IfBis inaccessible, ambiguous, or virtual base ofDor is a base of some intermediate virtual base ofD, the conversion is ill-formed (won't compile). The resulting pointer can be dereferenced with aDobject, and it will access the member within theBbase subobject of thatDobject. The null pointer value is converted to the null pointer value of the destination type.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
[править] Булевых преобразований
Prvalues интегральных с плавающей точкой, незаданной перечисления, указатель и указатель на член типа могут быть преобразованы в prvalues типа bool.
Original:
Prvalues of integral, floating-point, unscoped enumeration, pointer, and pointer-to-member types can be converted to prvalues of type bool.
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.
Нулевое значение (для целых, с плавающей точкой, а незаданной перечисления) и нулевого указателя и нулевого указателя на член ценности становятся false. Все остальные значения становятся true.
Original:
The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true.
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.
Prvalue типа std::nullptr_t, в том числе
nullptr, могут быть преобразованы в prvalue типа bool. Полученное значение false. (начиная с C++11)Original:
Prvalue of type std::nullptr_t, including
nullptr, can be converted to prvalue of type bool. The resulting value is false. (начиная с 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.
[править] Квалификация преобразований
-
Tможет быть преобразован в указатель на prvalue более CV-квалифицированные же типаT(другими словами, константность могут быть добавлены)Original:A prvalue of type pointer toCV-квалификацию</div> typeOriginal:cv-qualifiedThe 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.Tcan be converted to prvalue pointer to a more cv-qualified same typeT(in other words, constness can be added)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Prvalue тип указателя на член резюме квалифицированных
Tтипа в классеXмогут быть преобразованы в prvalue указатель на член больше резюме квалифицированных типаTв классеX.Original:A prvalue of type pointer to member of cv-qualified typeTin classXcan be converted to prvalue pointer to member of more cv-qualified typeTin classX.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
"More" резюме квалифицированных означает, что
Original:
"More" cv-qualified means that
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.
- ' Неквалифицированный тип может быть преобразован в
constOriginal:unqualified type can be converted toconstThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - ' Неквалифицированный тип может быть преобразован в
volatileOriginal:unqualified type can be converted tovolatileThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - ' Неквалифицированный тип может быть преобразован в
const volatileOriginal:unqualified type can be converted toconst volatileThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
constтипа могут быть преобразованы вconst volatileOriginal:consttype can be converted toconst volatileThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
volatileтипа могут быть преобразованы вconst volatileOriginal:volatiletype can be converted toconst volatileThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
Для многоуровневых указателей, применяются следующие ограничения:
Original:
For multi-level pointers, the following restrictions apply:
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.
Многоуровневых
0 квалифицированных указатель на cv1
1 квалифицированных указатель на... cv1
n-1 квалифицированных указатель на cv1
n квалифицированных
0 квалифицированных указатель на cv2
1 квалифицированных указатель на... cv2
n-1 квалифицированных указатель на cv2
n квалифицированных
P1 указатель, который является cv10 квалифицированных указатель на cv1
1 квалифицированных указатель на... cv1
n-1 квалифицированных указатель на cv1
n квалифицированных
T можно преобразовать в многоуровневый P1 указатель, который является cv20 квалифицированных указатель на cv2
1 квалифицированных указатель на... cv2
n-1 квалифицированных указатель на cv2
n квалифицированных
T только еслиOriginal:
A multilevel pointer
0-qualified pointer to cv1
1-qualified pointer to ... cv1
n-1-qualified pointer to cv1
n-qualified
0-qualified pointer to cv2
1-qualified pointer to ... cv2
n-1-qualified pointer to cv2
n-qualified
P1 which is cv10-qualified pointer to cv1
1-qualified pointer to ... cv1
n-1-qualified pointer to cv1
n-qualified
T is convertible to a multilevel pointer P1 which is cv20-qualified pointer to cv2
1-qualified pointer to ... cv2
n-1-qualified pointer to cv2
n-qualified
T only ifThe 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.
- Число
nуровней одинаковы для обоих указателейOriginal:The number of levelsnis the same for both pointersThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Если есть const в cv1
k квалификации на определенном уровне (кроме нулевого уровня) P1, есть const в том же cv2
k уровне P2Original:If there is a const in the cv1
k qualification at some level (other than level zero) of P1, there is a const in the same level cv2
k of P2The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Если есть volatile в cv1
k квалификации на определенном уровне (кроме нулевого уровня) P1, есть volatile в том же cv2
klevel Р2Original:If there is a volatile in the cv1
k qualification at some level (other than level zero) of P1, there is a volatile in the same cv2
klevel of P2The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Если на каком-то уровне
kCV-квалификации различаются междуP1иP2, то должно быть константным в каждом уровне (кроме уровня нуля)P2до K: cv2
1, cv2
2 ... cv2
k.Original:If at some levelkthe cv-qualifications are different betweenP1andP2, then there must be a const at every single level (other than level zero) ofP2up until k: cv2
1, cv2
2 ... cv2
k.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Те же правила применяются к многоуровневых указателей на члены и многоуровневые смешанные указателей на объекты и указатели на члены.Original:Same rules apply to multi-level pointers to members and multi-level mixed pointers to objects and pointers to members.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Уровень нуля рассмотрены правила для не-многоуровневая преобразования квалификации.Original:Level zero is addressed by the rules for non-multilevel qualification conversions.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
В частности, это запрещает переход от
T** в const T**, но преобразование в const T* const* разрешено.Original:
In particular, this forbids the conversion from
T** to const T**, but conversion to const T* const* is allowed.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.
[править] Безопасный BOOL проблемы
До введения явных функций преобразования в C + +11, проектирование класс, должны быть доступны в логический контекст (например, if(obj) { ... представляет собой проблему: при определенной пользователем функции преобразования, такие как T::operator bool() const;, неявные преобразования последовательностей позволило дополнительных стандартных Преобразование последовательности после этого вызова функции, что означает, что результирующая bool может быть преобразован в int, позволяя таким кодом, как obj << 1; или int i=test;.
Original:
Until the introduction of explicit conversion functions in C++11, designing a class that should be usable in boolean contexts (e.g. if(obj) { ... presented a problem: given a user-defined conversion function, such as T::operator bool() const;, the implicit conversion sequence allowed one additional standard conversion sequence after that function call, which means the resultant bool could be converted to int, allowing such code as obj << 1; or int i=test;.
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.
Одним из первых решений для этого можно увидеть в std::basic_ios, который определяет operator! и operator void*()(до C++11), так что код таких как if(std::cin) {... компилирует, потому что void* конвертируется в bool, но int n = std::cout; не компилируется, потому что void* не конвертируемых в int. Это еще ерунда позволяет кодом, таких как delete std::cout; для компиляции, и многие заранее C + +11 сторонних библиотек были разработаны с более сложные решения, известные как Safe Bool idiom.
Original:
One early solution for this can be seen in std::basic_ios, which defines operator! and operator void*()(до C++11), so that the code such as if(std::cin) {... compiles because void* is convertible to bool, but int n = std::cout; does not compile because void* is not convertible to int. This still allows nonsense code such as delete std::cout; to compile, and many pre-C++11 third party libraries were designed with a more elaborate solution, known as the Safe Bool idiom.
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.