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

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

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

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

2009. ISBN 0-321-54372-6.[Stroustrup,2010a] B. Stroustrup: The C++11 FAQ. www.stroustrup.com/C++11FAQ.html.[Stroustrup,2010b] B. Stroustrup: The C++0x ‘‘Remove Concepts’’ Decision. Dr. Dobb’s Journal. July 2009.[Stroustrup,2012a] B. Stroustrup and A. Sutton: A Concept Design for the STL. WG21 Technical Report N3351==12-0041. January 2012.[Stroustrup,2012b] B. Stroustrup: Software Development for Infrastructure. Computer. January2012. doi:10.1109/MC.2011.353.[Sutton,2011]A. Sutton and B. Stroustrup: Design of Concept Libraries for C++. Proc.SLE 2011 (International Conference on Software Language Engineering).July 2011.[Tanenbaum,2007] Andrew S. Tanenbaum: Modern Operating Systems, Third Edition.

PrenticeHall. Upper Saddle River, New Jersey. 2007. ISBN 0-13-600663-9.[Tsafrir,2009]Dan Tsafrir et al.: Minimizing Dependencies within Generic Classes forFaster and Smaller Programs. ACM OOPSLA’09. October 2009.[Unicode,1996]The Unicode Consortium: The Unicode Standard, Version 2.0. AddisonWesley. Reading, Massachusetts. 1996. ISBN 0-201-48345-9.[UNIX,1985]UNIX Time-Sharing System: Programmer’s Manual. Research Version,Tenth Edition. AT&T Bell Laboratories, Murray Hill, New Jersey. February1985.[Vandevoorde,2002] David Vandevoorde and Nicolai M.

Josuttis: C++ Templates: The CompleteGuide. Addison-Wesley. 2002. ISBN 0-201-73484-2.[Veldhuizen,1995]Todd Veldhuizen: Expression Templates. The C++ Report. June 1995.[Veldhuizen,2003]Todd L. Veldhuizen: C++ Templates are Turing Complete. Indiana University Computer Science Technical Report. 2003.[Vitter,1985]Jefferey Scott Vitter: Random Sampling with a Reservoir. ACM Transactions on Mathematical Software, Vol. 11, No. 1.

1985.[WG21]ISO SC22/WG21 The C++ Programming Language Standards Committee:Document Archive. www.open-std.org/jtc1/sc22/wg21.[Williams,2012]Anthony Williams: C++ Concurrency in Action – Practical Multithreading.Manning Publications Co. ISBN 978-1933988771.[Wilson,1996]Gregory V. Wilson and Paul Lu (editors): Parallel Programming Using C++.The MIT Press. Cambridge, Mass. 1996.

ISBN 0-262-73118-5.[Wood,1999]Alistair Wood: Introduction to Numerical Analysis. Addison-Wesley. Reading, Massachusetts. 1999. ISBN 0-201-34291-X.[Woodward,1974]P. M. Woodward and S. G. Bond: Algol 68-R Users Guide. Her Majesty’sStationery Office. London. 1974.2A Tour of C++: The BasicsThe first thing we do, let’skill all the language lawyers.– Henry VI, Part II••••••IntroductionThe BasicsHello, World!; Types, Variables, and Arithmetic; Constants; Tests and Loops; Pointers,Arrays, and LoopsUser-Defined TypesStructures; Classes; EnumerationsModularitySeparate Compilation; Namespaces; Error HandlingPostscriptAdvice2.1 IntroductionThe aim of this chapter and the next three is to give you an idea of what C++ is, without going intoa lot of details. This chapter informally presents the notation of C++, C++’s model of memory andcomputation, and the basic mechanisms for organizing code into a program.

These are the language facilities supporting the styles most often seen in C and sometimes called procedural programming. Chapter 3 follows up by presenting C++’s abstraction mechanisms. Chapter 4 andChapter 5 give examples of standard-library facilities.The assumption is that you have programmed before. If not, please consider reading a textbook, such as Programming: Principles and Practice Using C++ [Stroustrup,2009], before continuing here. Even if you have programmed before, the language you used or the applications youwrote may be very different from the style of C++ presented here. If you find this ‘‘lightning tour’’confusing, skip to the more systematic presentation starting in Chapter 6.38A Tour of C++: The BasicsChapter 2This tour of C++ saves us from a strictly bottom-up presentation of language and library facilities by enabling the use of a rich set of facilities even in early chapters.

For example, loops are notdiscussed in detail until Chapter 10, but they will be used in obvious ways long before that. Similarly, the detailed description of classes, templates, free-store use, and the standard library arespread over many chapters, but standard-library types, such as vector, string, complex, map,unique_ptr, and ostream, are used freely where needed to improve code examples.As an analogy, think of a short sightseeing tour of a city, such as Copenhagen or New York. Injust a few hours, you are given a quick peek at the major attractions, told a few background stories,and usually given some suggestions about what to see next. You do not know the city after such atour.

You do not understand all you have seen and heard. To really know a city, you have to live init, often for years. However, with a bit of luck, you will have gained a bit of an overview, a notionof what is special about the city, and ideas of what might be of interest to you.

After the tour, thereal exploration can begin.This tour presents C++ as an integrated whole, rather than as a layer cake. Consequently, itdoes not identify language features as present in C, part of C++98, or new in C++11. Such historical information can be found in §1.4 and Chapter 44.2.2 The BasicsC++ is a compiled language. For a program to run, its source text has to be processed by a compiler, producing object files, which are combined by a linker yielding an executable program. AC++ program typically consists of many source code files (usually simply called source files).source file 1compileobject file 1source file 2compileobject file 2linkexecutable fileAn executable program is created for a specific hardware/system combination; it is not portable,say, from a Mac to a Windows PC. When we talk about portability of C++ programs, we usuallymean portability of source code; that is, the source code can be successfully compiled and run on avariety of systems.The ISO C++ standard defines two kinds of entities:• Core language features, such as built-in types (e.g., char and int) and loops (e.g., for-statements and while-statements)• Standard-library components, such as containers (e.g., vector and map) and I/O operations(e.g., << and getline())The standard-library components are perfectly ordinary C++ code provided by every C++ implementation.

That is, the C++ standard library can be implemented in C++ itself (and is with veryminor uses of machine code for things such as thread context switching). This implies that C++ issufficiently expressive and efficient for the most demanding systems programming tasks.C++ is a statically typed language. That is, the type of every entity (e.g., object, value, name,and expression) must be known to the compiler at its point of use. The type of an object determinesthe set of operations applicable to it.Section 2.2.1Hello, World!392.2.1 Hello, World!The minimal C++ program isint main() { }// the minimal C++ programThis defines a function called main, which takes no arguments and does nothing (§15.4).Curly braces, { }, express grouping in C++.

Here, they indicate the start and end of the functionbody. The double slash, //, begins a comment that extends to the end of the line. A comment is forthe human reader; the compiler ignores comments.Every C++ program must have exactly one global function named main(). The program startsby executing that function. The int value returned by main(), if any, is the program’s return value to‘‘the system.’’ If no value is returned, the system will receive a value indicating successful completion.

A nonzero value from main() indicates failure. Not every operating system and executionenvironment make use of that return value: Linux/Unix-based environments often do, but Windows-based environments rarely do.Typically, a program produces some output. Here is a program that writes Hello, World!:#include <iostream>int main(){std::cout << "Hello, World!\n";}The line #include <iostream> instructs the compiler to include the declarations of the standardstream I/O facilities as found in iostream. Without these declarations, the expressionstd::cout << "Hello, World!\n"would make no sense.

The operator << (‘‘put to’’) writes its second argument onto its first. In thiscase, the string literal "Hello, World!\n" is written onto the standard output stream std::cout. A stringliteral is a sequence of characters surrounded by double quotes. In a string literal, the backslashcharacter \ followed by another character denotes a single ‘‘special character.’’ In this case, \n is thenewline character, so that the characters written are Hello, World! followed by a newline.The std:: specifies that the name cout is to be found in the standard-library namespace (§2.4.2,Chapter 14). I usually leave out the std:: when discussing standard features; §2.4.2 shows how tomake names from a namespace visible without explicit qualification.Essentially all executable code is placed in functions and called directly or indirectly frommain().

For example:#include <iostream>using namespace std;double square(double x){return x∗x;}// make names from std visible without std:: (§2.4.2)// square a double precision floating-point number40A Tour of C++: The BasicsChapter 2void print_square(double x){cout << "the square of " << x << " is " << square(x) << "\n";}int main(){print_square(1.234);}// print: the square of 1.234 is 1.52276A ‘‘return type’’ void indicates that a function does not return a value.2.2.2 Types, Variables, and ArithmeticEvery name and every expression has a type that determines the operations that may be performedon it. For example, the declarationint inch;specifies that inch is of type int; that is, inch is an integer variable.A declaration is a statement that introduces a name into the program.

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

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

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

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