Главная » Просмотр файлов » Стандарт C++ 98

Стандарт C++ 98 (1119566), страница 20

Файл №1119566 Стандарт C++ 98 (Стандарт C++ 98) 20 страницаСтандарт C++ 98 (1119566) страница 202019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 20)

If the sourcevalue can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination values, the result of the conversion is animplementation-defined choice of either of those values. Otherwise, the behavior is undefined.2The conversions allowed as floating point promotions are excluded from the set of floating point conversions.4.9 Floating-integral conversions[conv.fpint]1An rvalue of a floating point type can be converted to an rvalue of an integer type. The conversion truncates; that is, the fractional part is discarded.

The behavior is undefined if the truncated value cannot berepresented in the destination type. [Note: If the destination type is bool, see 4.12. ]2An rvalue of an integer type or of an enumeration type can be converted to an rvalue of a floating pointtype. The result is exact if possible. Otherwise, it is an implementation-defined choice of either the nextlower or higher representable value.

[Note: loss of precision occurs if the integral value cannot be represented exactly as a value of the floating type. ] If the source type is bool, the value false is converted tozero and the value true is converted to one.4.10 Pointer conversions[conv.ptr]1A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates tozero.

A null pointer constant can be converted to a pointer type; the result is the null pointer value of thattype and is distinguishable from every other value of pointer to object or pointer to function type. Two nullpointer values of the same type shall compare equal. The conversion of a null pointer constant to a pointerto cv-qualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification conversion (4.4).2An rvalue of type “pointer to cv T,” where T is an object type, can be converted to an rvalue of type“pointer to cv void.” The result of converting a “pointer to cv T” to a “pointer to cv void” points to thestart of the storage location where the object of type T resides, as if the object is a most derived object (1.8)of type T (that is, not a base class subobject).3An rvalue of type “pointer to cv D,” where D is a class type, can be converted to an rvalue of type “pointerto cv B,” where B is a base class (clause 10) of D.

If B is an inaccessible (clause 11) or ambiguous (10.2)base class of D, a program that necessitates this conversion is ill-formed. The result of the conversion is apointer to the base class sub-object of the derived class object. The null pointer value is converted to thenull pointer value of the destination type.60© ISO/IEC4 Standard conversions4.11 Pointer to member conversionsISO/IEC 14882:1998(E)4.11 Pointer to member conversions[conv.mem]1A null pointer constant (4.10) can be converted to a pointer to member type; the result is the null memberpointer value of that type and is distinguishable from any pointer to member not created from a null pointerconstant. Two null member pointer values of the same type shall compare equal.

The conversion of a nullpointer constant to a pointer to member of cv-qualified type is a single conversion, and not the sequence ofa pointer to member conversion followed by a qualification conversion (4.4).2An rvalue of type “pointer to member of B of type cv T,” where B is a class type, can be converted to anrvalue of type “pointer to member of D of type cv T,” where D is a derived class (clause 10) of B.

If B is aninaccessible (clause 11), ambiguous (10.2) or virtual (10.1) base class of D, a program that necessitates thisconversion is ill-formed. The result of the conversion refers to the same member as the pointer to memberbefore the conversion took place, but it refers to the base class member as if it were a member of thederived class. The result refers to the member in D’s instance of B.

Since the result has type “pointer tomember of D of type cv T,” it can be dereferenced with a D object. The result is the same as if the pointer tomember of B were dereferenced with the B sub-object of D. The null member pointer value is converted tothe null member pointer value of the destination type.52)4.12 Boolean conversions1[conv.bool]An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue oftype bool. A zero value, null pointer value, or null member pointer value is converted to false; anyother value is converted to true.__________________52) The rule for conversion of pointers to members (from pointer to member of base to pointer to member of derived) appears invertedcompared to the rule for pointers to objects (from pointer to derived to pointer to base) (4.10, clause 10). This inversion is necessary toensure type safety. Note that a pointer to member is not a pointer to object or a pointer to function and the rules for conversions ofsuch pointers do not apply to pointers to members.

In particular, a pointer to member cannot be converted to a void*.61ISO/IEC 14882:1998(E)©(Blank page)62ISO/IEC© ISO/IECISO/IEC 14882:1998(E)5 Expressions5 Expressions5 Expressions[expr]1[Note: Clause 5 defines the syntax, order of evaluation, and meaning of expressions. An expression is asequence of operators and operands that specifies a computation.

An expression can result in a value andcan cause side effects.2Operators can be overloaded, that is, given meaning when applied to expressions of class type (clause 9) orenumeration type (7.2). Uses of overloaded operators are transformed into function calls as described in13.5. Overloaded operators obey the rules for syntax specified in clause 5, but the requirements of operandtype, lvalue, and evaluation order are replaced by the rules for function call. Relations between operators,such as ++a meaning a+=1, are not guaranteed for overloaded operators (13.5), and are not guaranteed foroperands of type bool.

—end note]3Clause 5 defines the effects of operators when applied to types for which they have not been overloaded.Operator overloading shall not modify the rules for the built-in operators, that is, for operators applied totypes for which they are defined by this Standard. However, these built-in operators participate in overloadresolution, and as part of that process user-defined conversions will be considered where necessary to convert the operands to types appropriate for the built-in operator. If a built-in operator is selected, such conversions will be applied to the operands before the operation is considered further according to the rules inclause 5; see 13.3.1.2, 13.6.4Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.53) Between the previousand next sequence point a scalar object shall have its stored value modified at most once by the evaluationof an expression.

Furthermore, the prior value shall be accessed only to determine the value to be stored.The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a fullexpression; otherwise the behavior is undefined. [Example:i = v[i++];i = 7, i++, i++;// the behavior is unspecified// i becomes 9i = ++i + 1;i = i + 1;// the behavior is unspecified// the value of i is incremented—end example]5If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined, unless such an expression is a constant expression(5.19), in which case the program is ill-formed. [Note: most existing implementations of C++ ignore integer overflows.

Treatment of division by zero, forming a remainder using a zero divisor, and all floatingpoint exceptions vary among machines, and is usually adjustable by a library function. ]6If an expression initially has the type “reference to T” (8.3.2, 8.5.3), the type is adjusted to “T” prior to anyfurther analysis, the expression designates the object or function denoted by the reference, and the expression is an lvalue.7An expression designating an object is called an object-expression.8Whenever an lvalue expression appears as an operand of an operator that expects an rvalue for that operand,the lvalue-to-rvalue (4.1), array-to-pointer (4.2), or function-to-pointer (4.3) standard conversions areapplied to convert the expression to an rvalue.

[Note: because cv-qualifiers are removed from the type ofan expression of non-class type when the expression is converted to an rvalue, an lvalue expression of typeconst int can, for example, be used where an rvalue expression of type int is required. ]__________________53) The precedence of operators is not directly specified, but it can be derived from the syntax.63ISO/IEC 14882:1998(E)5 Expressions9© ISO/IEC5 ExpressionsMany binary operators that expect operands of arithmetic or enumeration type cause conversions and yieldresult types in a similar way.

The purpose is to yield a common type, which is also the type of the result.This pattern is called the usual arithmetic conversions, which are defined as follows:— If either operand is of type long double, the other shall be converted to long double.— Otherwise, if either operand is double, the other shall be converted to double.— Otherwise, if either operand is float, the other shall be converted to float.— Otherwise, the integral promotions (4.5) shall be performed on both operands.54)— Then, if either operand is unsigned long the other shall be converted to unsigned long.— Otherwise, if one operand is a long int and the other unsigned int, then if a long int can represent all the values of an unsigned int, the unsigned int shall be converted to a long int;otherwise both operands shall be converted to unsigned long int.— Otherwise, if either operand is long, the other shall be converted to long.— Otherwise, if either operand is unsigned, the other shall be converted to unsigned.[Note: otherwise, the only remaining case is that both operands are int ]10The values of the floating operands and the results of floating expressions may be represented in greaterprecision and range than that required by the type; the types are not changed thereby.55)5.1 Primary expressions1[expr.prim]Primary expressions are literals, names, and names qualified by the scope resolution operator ::.primary-expression:literalthis( expression )id-expressionid-expression:unqualified-idqualified-idunqualified-id:identifieroperator-function-idconversion-function-id˜ class-nametemplate-id2A literal is a primary expression.

Характеристики

Тип файла
PDF-файл
Размер
2,05 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6417
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее