Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 59

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 59 страницаB. Stroustrup - The C++ Programming Language (794319) страница 592019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Each operator is followed byone or more names commonly used for it and an example of its use. In these tables:• A name is an identifier (e.g., sum and map), an operator name (e.g., operator int, operator+,and operator"" km), or the name of a template specialization (e.g., sort<Record> andarray<int,10>), possibly qualified using :: (e.g., std::vector and vector<T>::operator[]).• A class-name is the name of a class (including decltype(expr) where expr denotes a class).• A member is a member name (including the name of a destructor or a member template).• An object is an expression yielding a class object.• A pointer is an expression yielding a pointer (including this and an object of that type thatsupports the pointer operation).• An expr is an expression, including a literal (e.g., 17, "mouse", and true)• An expr-list is a (possibly empty) list of expressions.• An lvalue is an expression denoting a modifiable object (§6.4.1).• A type can be a fully general type name (with ∗, (), etc.) only when it appears in parentheses; elsewhere, there are restrictions (§iso.A).• A lambda-declarator is a (possibly empty, comma-separated) list of parameters optionallyfollowed by the mutable specifier, optionally followed by a noexcept specifier, optionally followed by a return type (§11.4).• A capture-list is a (possibly empty) list specifying context dependencies (§11.4).• A stmt-list is a (possibly empty) list of statements (§2.2.4, Chapter 9).The syntax of expressions is independent of operand types.

The meanings presented here applywhen the operands are of built-in types (§6.2.1). In addition, you can define meanings for operatorsapplied to operands of user-defined types (§2.3, Chapter 18).A table can only approximate the rules of the grammar. For details, see §iso.5 and §iso.A.Operator Summary (continues) (§iso.5.1)Parenthesized expressionLambdaScope resolutionScope resolutionGlobalexpr )capture-list ] lambda-declarator { stmt-List }class-name :: membernamespace-name :: member:: name([§11.4§16.2.3§14.2.1§14.2.1Each box holds operators with the same precedence. Operators in higher boxes have higher precedence. For example, N::x.m means (N::m).m rather than the illegal N::(x.m).256ExpressionsChapter 10Operator Summary (continued, continues)Member selectionMember selectionSubscriptingFunction callValue constructionFunction-style type conversionPost incrementPost decrementType identificationRun-time type identificationRun-time checked conversionCompile-time checked conversionUnchecked conversionconst conversionSize of objectSize of typeSize of parameter packAlignment of typePre incrementPre decrementComplementNotUnary minusUnary plusAddress ofDereferenceCreate (allocate)Create (allocate and initialize)Create (allocate and initialize)Create (place)Create (place and initialize)Create (place and initialize)Destroy (deallocate)Destroy arrayCan expression throw?Cast (type conversion)Member selectionMember selectionobject .

memberpointer −> memberpointer [ expr ]expr ( expr-list )type { expr-list }type ( expr-list )lvalue ++lvalue −−typeid ( type )typeid ( expr )dynamic_cast < type > ( expr )static_cast < type > ( expr )reinterpret_cast < type > ( expr )const_cast < type > ( expr )sizeof exprsizeof ( type )sizeof...

namealignof ( type )++ lvalue−− lvalue˜ expr! expr− expr+ expr& lvalue∗ exprnew typenew type ( expr-list )new type { expr-list }new ( expr-list ) typenew ( expr-list ) type ( expr-list )new ( expr-list ) type { expr-list }delete pointerdelete [] pointernoexcept ( expr )( type ) exprobject .∗ pointer-to-memberpointer −>∗ pointer-to-member§16.2.3§16.2.3§7.3§12.2§11.3.2§11.5.4§11.1.4§11.1.4§22.5§22.5§22.2.1§11.5.2§11.5.2§11.5.2§6.2.8§6.2.8§28.6.2§6.2.9§11.1.4§11.1.4§11.1.2§11.1.1§2.2.2§2.2.2§7.2§7.2§11.2§11.2§11.2§11.2.4§11.2.4§11.2.4§11.2§11.2.2§13.5.1.2§11.5.3§20.6§20.6For example, postfix ++ has higher precedence than unary ∗, so ∗p++ means ∗(p++), not (∗p)++.Section 10.3Operator Summary257Operator Summary (continued)MultiplyDivideModulo (remainder)Add (plus)Subtract (minus)Shift leftShift rightLess thanLess than or equalGreater thanGreater than or equalEqualNot equalBitwise andBitwise exclusive-orBitwise inclusive-orLogical andLogical inclusive orConditional expressionListThrow exceptionSimple assignmentMultiply and assignDivide and assignModulo and assignAdd and assignSubtract and assignShift left and assignShift right and assignBitwise and and assignBitwise inclusive-or and assignBitwise exclusive-or and assigncomma (sequencing)expr ∗ exprexpr / exprexpr % exprexpr + exprexpr − exprexpr << exprexpr >> exprexpr < exprexpr <= exprexpr > exprexpr >= exprexpr == exprexpr != exprexpr & exprexpr ˆ exprexpr | exprexpr && exprexpr || exprexpr ? expr : expr{ expr-list }throw exprlvalue = exprlvalue ∗= exprlvalue /= exprlvalue %= exprlvalue += exprlvalue −= exprlvalue <<= exprlvalue >>= exprlvalue &= exprlvalue |= exprlvalue ˆ= exprexpr , expr§10.2.1§10.2.1§10.2.1§10.2.1§10.2.1§11.1.2§11.1.2§2.2.2§2.2.2§2.2.2§2.2.2§2.2.2§2.2.2§11.1.2§11.1.2§11.1.2§11.1.1§11.1.1§11.1.3§11.3§13.5§10.2.1§10.2.1§10.2.1§10.2.1§10.2.1§10.2.1§10.2.1§10.2.1§10.2.1§10.2.1§10.2.1§10.3.2For example: a+b∗c means a+(b∗c) rather than (a+b)∗c because ∗ has higher precedence than +.Unary operators and assignment operators are right-associative; all others are left-associative.For example, a=b=c means a=(b=c) whereas a+b+c means (a+b)+c.A few grammar rules cannot be expressed in terms of precedence (also known as bindingstrength) and associativity.

For example, a=b<c?d=e:f=g means a=((b<c)?(d=e):(f=g)), but you need tolook at the grammar (§iso.A) to determine that.258ExpressionsChapter 10Before applying the grammar rules, lexical tokens are composed from characters. The longestpossible sequence of characters is chosen to make a token. For example, && is a single operator,rather than two & operators, and a+++1 means (a ++) + 1. This is sometimes called the Max Munchrule.Token Summary (§iso.2.7)Token ClassIdentifierKeywordCharacter literalInteger literalFloating-point literalString literalOperatorPunctuationPreprocessor notationExamplesvector, foo_bar, x3int, for, virtual’x’, \n’, ’U’\UFADEFADE’12, 012, 0x121.2, 1.2e−3, 1.2L"Hello!", R"("World"!)"+=, %, <<;, ,, {, }, (, )#, ##Reference§6.3.3§6.3.3.1§6.2.3.2§6.2.4.1§6.2.5.1§7.3.2§10.3§12.6Whitespace characters (e.g., space, tab, and newline) can be token separators (e.g., int count is akeyword followed by an identifier, rather than intcount) but are otherwise ignored.Some characters from the basic source character set (§6.1.2), such as |, are not convenient totype on some keywords.

Also, some programmers find it odd to use of symbols, such as && and ˜,for basic logical operations. Consequently, a set of alternative representation are provided askeywords:Alternative Representation (§iso.2.12)and&and_eq&=bitand&bitor|compl˜not!not_eq!=or|or_eq|=xorˆxor_eqˆ=For examplebool b = not (x or y) and z;int x4 = ˜ (x1 bitor x2) bitand x3;is equivalent tobool b = !(x || y) && z;int x4 = ˜(x1 | x2) & x3;Note that and= is not equivalent to &=; if you prefer keywords, you must write and_eq.10.3.1 ResultsThe result types of arithmetic operators are determined by a set of rules known as ‘‘the usual arithmetic conversions’’ (§10.5.3).

The overall aim is to produce a result of the ‘‘largest’’ operand type.For example, if a binary operator has a floating-point operand, the computation is done using floating-point arithmetic and the result is a floating-point value. Similarly, if it has a long operand, thecomputation is done using long integer arithmetic, and the result is a long. Operands that aresmaller than an int (such as bool and char) are converted to int before the operator is applied.Section 10.3.1Results259The relational operators, ==, <=, etc., produce Boolean results.

The meaning and result type ofuser-defined operators are determined by their declarations (§18.2).Where logically feasible, the result of an operator that takes an lvalue operand is an lvaluedenoting that lvalue operand. For example:void f(int x, int y){int j = x = y;int∗ p = &++x;int∗ q = &(x++);int∗ p2 = &(x>y?x:y);int& r = (x<y)?x:1;}// the value of x=y is the value of x after the assignment// p points to x// error : x++ is not an lvalue (it is not the value stored in x)// address of the int with the larger value// error : 1 is not an lvalueIf both the second and third operands of ?: are lvalues and have the same type, the result is of thattype and is an lvalue. Preserving lvalues in this way allows greater flexibility in using operators.This is particularly useful when writing code that needs to work uniformly and efficiently with bothbuilt-in and user-defined types (e.g., when writing templates or programs that generate C++ code).The result of sizeof is of an unsigned integral type called size_t defined in <cstddef>.

The resultof pointer subtraction is of a signed integral type called ptrdiff_t defined in <cstddef>.Implementations do not have to check for arithmetic overflow and hardly any do. For example:void f(){int i = 1;while (0 < i) ++i;cout << "i has become negative!" << i << '\n';}This will (eventually) try to increase i past the largest integer. What happens then is undefined, buttypically the value ‘‘wraps around’’ to a negative number (on my machine −2147483648). Similarly,the effect of dividing by zero is undefined, but doing so usually causes abrupt termination of theprogram. In particular, underflow, overflow, and division by zero do not throw standard exceptions(§30.4.1.1).10.3.2 Order of EvaluationThe order of evaluation of subexpressions within an expression is undefined.

In particular, you cannot assume that the expression is evaluated left-to-right. For example:int x = f(2)+g(3);// undefined whether f() or g() is called firstBetter code can be generated in the absence of restrictions on expression evaluation order. However, the absence of restrictions on evaluation order can lead to undefined results. For example:int i = 1;v[i] = i++; // undefined resultThe assignment may be evaluated as either v[1]=1 or v[2]=1 or may cause some even stranger behavior.

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

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

Список файлов книги

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