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

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

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

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

The corresponding definitions are found in theappropriate .cpp files.I added standard-library headers as needed for the declarations in dc.h, but I did not add declarations (such as using-declarations) needed only for the convenience of an individual .cpp file.Leaving out the actual code, lexer.cpp will look something like this:// lexer.cpp:#include "dc.h"#include <cctype>#include <iostream>// redundant: in dc.hLexer::Token_stream ts;Lexer::Token Lexer::Token_stream::get() { /* ... */ }Lexer::Token& Lexer::Token_stream::current() { /* ...

*/ }I used explicit qualification, Lexer::, for the definitions rather that simply enclosing them all innamespace Lexer { /* ... */ }That avoids the possibility of accidentally adding new members to Lexer. On the other hand, had Iwanted to add members to Lexer that were not part of its interface, I would have had to reopen thenamespace (§14.2.5).Using headers in this manner ensures that every declaration in a header will at some point beincluded in the file containing its definition. For example, when compiling lexer.cpp the compilerwill be presented with:namespace Lexer { // from dc.h// ...class Token_stream {public:Token get();// ...};}434Source Files and ProgramsChapter 15// ...Lexer::Token Lexer::Token_stream::get() { /* ...

*/ }This ensures that the compiler will detect any inconsistencies in the types specified for a name. Forexample, had get() been declared to return a Token, but defined to return an int, the compilation oflexer.cpp would have failed with a type-mismatch error.

If a definition is missing, the linker willcatch the problem. If a declaration is missing, some .cpp files will fail to compile.File parser.cpp will look like this:// parser.cpp:#include "dc.h"double Parser::prim(bool get) { /* ... */ }double Parser::term(bool get) { /* ... */ }double Parser::expr(bool get) { /* ... */ }File table.cpp will look like this:// table.cpp:#include "dc.h"std::map<std::string,double> Table::table;The symbol table is a standard-library map.File error.cpp becomes:// error.cpp:#include "dg.h"// any more #includes or declarationsint Error::no_of_errors;double Error::error(const string& s) { /* ... */ }Finally, file main.cpp will look like this:// main.cpp:#include "dc.h"#include <sstream>#include <iostream>// redundant: in dc.hvoid Driver::calculate() { /* ...

*/ }int main(int argc, char∗ argv[]) { /* ... */ }To be recognized as the main() of the program, main() must be a global function (§2.2.1, §15.4), sono namespace is used here.Section 15.3.1Single-Header Organization435The physical structure of the system can be presented like this:<sstream><map><string><cctype><iostream>lexer.cpperror.cppdc.htable.cppparser.cppmain.cppThe headers on the top are all headers for standard-library facilities. For many forms of programanalysis, these libraries can be ignored because they are well known and stable. For tiny programs,the structure can be simplified by moving all #include directives to the common header.

Similarly,for a small program, separating out error.cpp and table.cpp from main.cpp would often be excessive.This single-header style of physical partitioning is most useful when the program is small andits parts are not intended to be used separately. Note that when namespaces are used, the logicalstructure of the program is still represented within dc.h. If namespaces are not used, the structure isobscured, although comments can be a help.For larger programs, the single-header-file approach is unworkable in a conventional file-baseddevelopment environment.

A change to the common header forces recompilation of the whole program, and updates of that single header by several programmers are error-prone. Unless strongemphasis is placed on programming styles relying heavily on namespaces and classes, the logicalstructure deteriorates as the program grows.15.3.2 Multiple-Header OrganizationAn alternative physical organization lets each logical module have its own header defining the facilities it provides. Each .cpp file then has a corresponding .h file specifying what it provides (itsinterface). Each .cpp file includes its own .h file and usually also other .h files that specify what itneeds from other modules in order to implement the services advertised in the interface. This physical organization corresponds to the logical organization of a module.

The interface for users is putinto its .h file, the interface for implementers is put into a file suffixed _impl.h, and the module’s definitions of functions, variables, etc., are placed in .cpp files. In this way, the parser is representedby three files. The parser’s user interface is provided by parser.h:// parser.h:namespace Parser {double expr(bool get);}// interface for usersThe shared environment for the functionssented by parser_impl.h:expr(), prim(),andterm(),implementing the parser is pre-436Source Files and ProgramsChapter 15// parser_impl.h:#include "parser.h"#include "error.h"#include "lexer.h"using Error::error;using namespace Lexer;namespace Parser {double prim(bool get);double term(bool get);double expr(bool get);}// interface for implementersThe distinction between the user interface and the interface for implementers would be even clearerhad we used a Parser_impl namespace (§14.3.3).The user’s interface in header parser.h is #included to give the compiler a chance to check consistency (§15.3.1).The functions implementing the parser are stored in parser.cpp together with #include directivesfor the headers that the Parser functions need:// parser.cpp:#include "parser_impl.h"#include "table.h"using Table::table;double Parser::prim(bool get) { /* ...

*/ }double Parser::term(bool get) { /* ... */ }double Parser::expr(bool get) { /* ... */ }Graphically, the parser and the driver’s use of it look like this:parser.hlexer.herror.htable.hparser_impl.hmain.cppparser.cppAs intended, this is a rather close match to the logical structure described in §14.3.1. To simplifythis structure, we could have #included table.h in parser_impl.h rather than in parser.cpp. However,table.h is an example of something that is not necessary to express the shared context of the parserfunctions; it is needed only by their implementation.

In fact, it is used by just one function, prim(),Section 15.3.2Multiple-Header Organization437so if we were really keen on minimizing dependencies we could place prim() in its own .cpp file and#include table.h there only:parser.hlexer.herror.htable.hparser_impl.hparser.cppprim.cppSuch elaboration is not appropriate except for larger modules. For realistically sized modules, it iscommon to #include extra files where needed for individual functions.

Furthermore, it is notuncommon to have more than one _impl.h, since different subsets of the module’s functions needdifferent shared contexts.Please note that the _impl.h notation is not a standard or even a common convention; it is simplythe way I like to name things.Why bother with this more complicated scheme of multiple header files? It clearly requires farless thought simply to throw every declaration into a single header, as was done for dc.h.The multiple-header organization scales to modules several magnitudes larger than our toyparser and to programs several magnitudes larger than our calculator.

The fundamental reason forusing this type of organization is that it provides a better localization of concerns. When analyzingand modifying a large program, it is essential for a programmer to focus on a relatively small chunkof code. The multiple-header organization makes it easy to determine exactly what the parser codedepends on and to ignore the rest of the program. The single-header approach forces us to look atevery declaration used by any module and decide if it is relevant. The simple fact is that maintenance of code is invariably done with incomplete information and from a local perspective.

Themultiple-header organization allows us to work successfully ‘‘from the inside out’’ with only a localperspective. The single-header approach – like every other organization centered around a globalrepository of information – requires a top-down approach and will forever leave us wonderingexactly what depends on what.The better localization leads to less information needed to compile a module, and thus to fastercompiles. The effect can be dramatic.

I have seen compile times drop by a factor of 1000 as theresult of a simple dependency analysis leading to a better use of headers.15.3.2.1 Other Calculator ModulesThe remaining calculator modules can be organized similarly to the parser. However, those modules are so small that they don’t require their own _impl.h files. Such files are needed only wherethe implementation of a logical module consists of many functions that need a shared context (inaddition to what is provided to users).The error handler provides its interface in error.h:438Source Files and ProgramsChapter 15// error.h:#include<string>namespace Error {int Error::number_of_errors;double Error::error(const std::string&);}The implementation is found in error.cpp:// error.cpp:#include "error.h"int Error::number_of_errors;double Error::error(const std::string&) { /* ... */ }The lexer provides a rather large and messy interface:// lexer.h:#include<string>#include<iostream>namespace Lexer {enum class Kind : char {/* ...

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

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

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

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