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

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

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

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

This points to a problem: adding amonth is conceptually simple, so why is our code getting complicated? In this case, the reason isthat the d,m,y representation isn’t as convenient for the computer as it is for us. A better representation (for many purposes) would be simply a number of days since a defined ‘‘day zero’’ (e.g., January 1, 1970). That would make computation on Dates simple at the expense of complexity in providing output fit for humans.Note that assignment and copy initialization are provided by default (§16.2.2). Also, Datedoesn’t need a destructor because a Date owns no resources and requires no cleanup when it goesout of scope (§3.2.1.2).16.3.2 Helper FunctionsTypically, a class has a number of functions associated with it that need not be defined in the classitself because they don’t need direct access to the representation. For example:int diff(Date a, Date b);// number of days in the range [a,b) or [b,a)bool is_leapyear(int y);bool is_date(int d, Month m, int y);const Date& default_date();Date next_weekday(Date d);Date next_saturday(Date d);476ClassesChapter 16Defining such functions in the class itself would complicate the class interface and increase thenumber of functions that would potentially need to be examined when a change to the representation was considered.How are such functions ‘‘associated’’ with class Date? In early C++, as in C, their declarationswere simply placed in the same file as the declaration of class Date.

Users who needed Dates wouldmake them all available by including the file that defined the interface (§15.2.2). For example:#include "Date.h"In addition (or alternatively), we can make the association explicit by enclosing the class and itshelper functions in a namespace (§14.3.1):namespace Chrono {// facilities for dealing with timeclass Date { /* ... */};int diff(Date a, Date b);bool is_leapyear(int y);bool is_date(int d, Month m, int y);const Date& default_date();Date next_weekday(Date d);Date next_saturday(Date d);// ...}The Chrono namespace would naturally also contain related classes, such as Time and Stopwatch,and their helper functions.

Using a namespace to hold a single class is usually an overelaborationthat leads to inconvenience.Naturally, the helper function must be defined somewhere:bool Chrono::is_date(int d, Month m, int y){int ndays;switch (m) {case Month::feb:ndays = 28+is_leapyear(y);break;case Month::apr: case Month::jun: case Month::sep: case Month::nov:ndays = 30;break;case Month::jan: case Month::mar: case Month::may: case Month::jul:case Month::aug: case Month::oct: case Month::dec:ndays = 31;break;default:return false;}return 1<=d && d<=ndays;}Section 16.3.2Helper Functions477I’m deliberately being a bit paranoid here. A Month shouldn’t be outside the jan to dec range, but itis possible (someone might have been sloppy with a cast), so I check.The troublesome default_date finally becomes:const Date& Chrono::default_date(){static Date d {1,Month::jan,1970};return d;}16.3.3 Overloaded OperatorsIt is often useful to add functions to enable conventional notation.

For example,defines the equality operator, ==, to work for Dates:operator==()inline bool operator==(Date a, Date b)// equality{return a.day()==b.day() && a.month()==b.month() && a.year()==b.year();}Other obvious candidates are:bool operator!=(Date, Date);bool operator<(Date, Date);bool operator>(Date, Date);// ...// inequality// less than// greater thanDate& operator++(Date& d) { return d.add_day(1); }Date& operator−−(Date& d) { return d.add_day(−1); }// increase Date by one day// decrease Date by one dayDate& operator+=(Date& d, int n) { return d.add_day(n); }Date& operator−=(Date& d, int n) { return d.add_day(−n); }// add n days// subtract n daysDate operator+(Date d, int n) { return d+=n; }Date operator−(Date d, int n) { return d+=n; }// add n days// subtract n daysostream& operator<<(ostream&, Date d);istream& operator>>(istream&, Date& d);// output d// read into dThese operators are defined in Chrono together with Date to avoid overload problems and to benefitfrom argument-dependent lookup (§14.2.4).For Date, these operators can be seen as mere conveniences.

However, for many types – such ascomplex numbers (§18.3), vectors (§4.4.1), and function-like objects (§3.4.3, §19.2.2) – the use ofconventional operators is so firmly entrenched in people’s minds that their definition is almostmandatory. Operator overloading is discussed in Chapter 18.For Date, I was tempted to provide += and −= as member functions instead of add_day(). Had Idone so, I would have followed a common idiom (§3.2.1.1).Note that assignment and copy initialization are provided by default (§16.3, §17.3.3).478ClassesChapter 1616.3.4 The Significance of Concrete ClassesI call simple user-defined types, such as Date, concrete types to distinguish them from abstractclasses (§3.2.2) and class hierarchies (§20.4), and also to emphasize their similarity to built-in typessuch as int and char.

Concrete classes are used just like built-in types. Concrete types have alsobeen called value types and their use value-oriented programming. Their model of use and the‘‘philosophy’’ behind their design are quite different from what is often called object-oriented programming (§3.2.4, Chapter 21).The intent of a concrete type is to do a single, relatively simple thing well and efficiently. It isnot usually the aim to provide the user with facilities to modify the behavior of a concrete type. Inparticular, concrete types are not intended to display run-time polymorphic behavior (see §3.2.3,§20.3.2).If you don’t like some detail of a concrete type, you build a new one with the desired behavior.If you want to ‘‘reuse’’ a concrete type, you use it in the implementation of your new type exactlyas you would have used an int.

For example:class Date_and_time {private:Date d;Time t;public:Date_and_time(Date d, Time t);Date_and_time(int d, Date::Month m, int y, Time t);// ...};Alternatively, the derived class mechanism discussed in Chapter 20 can be used to define new typesfrom a concrete class by describing the desired differences. The definition of Vec from vector(§4.4.1.2) is an example of this. However, derivation from a concrete class should be done withcare and only rarely because of the lack of virtual functions and run-time type information(§17.5.1.4, Chapter 22).With a reasonably good compiler, a concrete class such as Date incurs no hidden overhead intime or space.

In particular, no indirection through pointers is necessary for access to objects ofconcrete classes, and no ‘‘housekeeping’’ data is stored in objects of concrete classes. The size of aconcrete type is known at compile time so that objects can be allocated on the run-time stack (thatis, without free-store operations). The layout of an object is known at compile time so that inliningof operations is trivially achieved. Similarly, layout compatibility with other languages, such as Cand Fortran, comes without special effort.A good set of such types can provide a foundation for applications.

In particular, they can beused to make<b>Текст обрезан, так как является слишком большим</b>.

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

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

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

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