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

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

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

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

It specifies a type for thenamed entity:• A type defines a set of possible values and a set of operations (for an object).• An object is some memory that holds a value of some type.• A value is a set of bits interpreted according to a type.• A variable is a named object.C++ offers a variety of fundamental types. For example:boolcharintdouble// Boolean, possible values are true and false// character, for example, 'a', ' z', and '9'// integer, for example, 1, 42, and 1066// double-precision floating-point number, for example, 3.14 and 299793.0Each fundamental type corresponds directly to hardware facilities and has a fixed size that determines the range of values that can be stored in it:bool:char:int:double:A char variable is of the natural size to hold a character on a given machine (typically an 8-bitbyte), and the sizes of other types are quoted in multiples of the size of a char.

The size of a type isimplementation-defined (i.e., it can vary among different machines) and can be obtained by thesizeof operator; for example, sizeof(char) equals 1 and sizeof(int) is often 4.The arithmetic operators can be used for appropriate combinations of these types:Section 2.2.2x+y+xx−y−xx∗yx/yx%yTypes, Variables, and Arithmetic41// plus// unar y plus// minus// unar y minus// multiply// divide// remainder (modulus) for integersSo can the comparison operators:x==yx!=yx<yx>yx<=yx>=y// equal// not equal// less than// greater than// less than or equal// greater than or equalIn assignments and in arithmetic operations, C++ performs all meaningful conversions (§10.5.3)between the basic types so that they can be mixed freely:void some_function(){double d = 2.2;int i = 7;d = d+i;i = d∗i;}// function that doesn’t return a value// initialize floating-point number// initialize integer// assign sum to d// assign product to i (truncating the double d*i to an int)Note that = is the assignment operator and == tests equality.C++ offers a variety of notations for expressing initialization, such as theuniversal form based on curly-brace-delimited initializer lists:=used above, and adouble d1 = 2.3;double d2 {2.3};complex<double> z = 1;complex<double> z2 {d1,d2};complex<double> z3 = {1,2};// a complex number with double-precision floating-point scalarsvector<int> v {1,2,3,4,5,6};// a vector of ints// the = is optional with { ...

}The = form is traditional and dates back to C, but if in doubt, use the general {}-list form (§6.3.5.2).If nothing else, it saves you from conversions that lose information (narrowing conversions; §10.5):int i1 = 7.2;int i2 {7.2};int i3 = {7.2};// i1 becomes 7// error: floating-point to integer conversion// error: floating-point to integer conversion (the = is redundant)A constant (§2.2.3) cannot be left uninitialized and a variable should only be left uninitialized inextremely rare circumstances. Don’t introduce a name until you have a suitable value for it.

Userdefined types (such as string, vector, Matrix, Motor_controller, and Orc_warrior) can be defined to beimplicitly initialized (§3.2.1.1).42A Tour of C++: The BasicsChapter 2When defining a variable, you don’t actually need to state its type explicitly when it can bededuced from the initializer:auto b = true;auto ch = 'x';auto i = 123;auto d = 1.2;auto z = sqrt(y);// a bool// a char// an int// a double// z has the type of whatever sqr t(y) returnsWith auto, we use the = syntax because there is no type conversion involved that might cause problems (§6.3.6.2).We use auto where we don’t have a specific reason to mention the type explicitly.

‘‘Specificreasons’’ include:• The definition is in a large scope where we want to make the type clearly visible to readersof our code.• We want to be explicit about a variable’s range or precision (e.g., double rather than float).Using auto, we avoid redundancy and writing long type names. This is especially important ingeneric programming where the exact type of an object can be hard for the programmer to knowand the type names can be quite long (§4.5.1).In addition to the conventional arithmetic and logical operators (§10.3), C++ offers more specific operations for modifying a variable:x+=y++xx−=y−−xx∗=yx/=yx%=y// x = x+y// increment: x = x+1// x = x-y// decrement: x = x-1// scaling: x = x*y// scaling: x = x/y// x = x%yThese operators are concise, convenient, and very frequently used.2.2.3 ConstantsC++ supports two notions of immutability (§7.5):• const: meaning roughly ‘‘I promise not to change this value’’ (§7.5).

This is used primarilyto specify interfaces, so that data can be passed to functions without fear of it being modified. The compiler enforces the promise made by const.• constexpr: meaning roughly ‘‘to be evaluated at compile time’’ (§10.4). This is used primarily to specify constants, to allow placement of data in memory where it is unlikely to be corrupted, and for performance.For example:const int dmv = 17;int var = 17;constexpr double max1 = 1.4∗square(dmv);constexpr double max2 = 1.4∗square(var);const double max3 = 1.4∗square(var);// dmv is a named constant// var is not a constant// OK if square(17) is a constant expression// error : var is not a constant expression// OK, may be evaluated at run timeSection 2.2.3double sum(const vector<double>&);vector<double> v {1.2, 3.4, 4.5};const double s1 = sum(v);constexpr double s2 = sum(v);Constants43// sum will not modify its argument (§2.2.5)// v is not a constant// OK: evaluated at run time// error : sum(v) not constant expressionFor a function to be usable in a constant expression, that is, in an expression that will be evaluatedby the compiler, it must be defined constexpr.

For example:constexpr double square(double x) { return x∗x; }To beconstexpr, a function must be rather simple: just a return-statement computing a value. Aconstexpr function can be used for non-constant arguments, but when that is done the result is not aconstant expression. We allow a constexpr function to be called with non-constant-expression argu-ments in contexts that do not require constant expressions, so that we don’t have to define essentially the same function twice: once for constant expressions and once for variables.In a few places, constant expressions are required by language rules (e.g., array bounds (§2.2.5,§7.3), case labels (§2.2.4, §9.4.2), some template arguments (§25.2), and constants declared usingconstexpr).

In other cases, compile-time evaluation is important for performance. Independently ofperformance issues, the notion of immutability (of an object with an unchangeable state) is animportant design concern (§10.4).2.2.4 Tests and LoopsC++ provides a conventional set of statements for expressing selection and looping.

For example,here is a simple function that prompts the user and returns a Boolean indicating the response:bool accept(){cout << "Do you want to proceed (y or n)?\n";char answer = 0;cin >> answer;// write question// read answerif (answer == 'y') return true;return false;}To match the << output operator (‘‘put to’’), the >> operator (‘‘get from’’) is used for input; cin isthe standard input stream. The type of the right-hand operand of >> determines what input isaccepted, and its right-hand operand is the target of the input operation.

The \n character at the endof the output string represents a newline (§2.2.1).The example could be improved by taking an n (for ‘‘no’’) answer into account:bool accept2(){cout << "Do you want to proceed (y or n)?\n";char answer = 0;cin >> answer;// write question// read answer44A Tour of C++: The BasicsChapter 2switch (answer) {case 'y':return true;case 'n':return false;default:cout << "I'll take that for a no.\n";return false;}}A switch-statement tests a value against a set of constants.

The case constants must be distinct, andif the value tested does not match any of them, the default is chosen. If no default is provided, noaction is taken if the value doesn’t match any case constant.Few programs are written without loops. For example, we might like to give the user a few triesto produce acceptable input:bool accept3(){int tries = 1;while (tries<4) {cout << "Do you want to proceed (y or n)?\n";char answer = 0;cin >> answer;// write question// read answerswitch (answer) {case 'y':return true;case 'n':return false;default:cout << "Sorry, I don't understand that.\n";++tries; // increment}}cout << "I'll take that for a no.\n";return false;}The while-statement executes until its condition becomes false.2.2.5 Pointers, Arrays, and LoopsAn array of elements of type char can be declared like this:char v[6];// array of 6 charactersSimilarly, a pointer can be declared like this:char∗ p;In declarations,// pointer to character[]means ‘‘array of’’ and∗means ‘‘pointer to.’’ All arrays have0as their lowerSection 2.2.5Pointers, Arrays, and Loops45bound, so v has six elements, v[0] to v[5].

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

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

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

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