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

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

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

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

For example:struct Link {Link∗ pre;Link∗ suc;int data;Link∗ insert(int x) // inser t x before this{return pre = new Link{pre,this,x};}466ClassesChapter 16void remove() // remove and destroy this{if (pre) pre−>suc = suc;if (suc) suc−>pre = pre;delete this;}// ...};Explicit use of this is required for access to members of base classes from a derived class that is atemplate (§26.3.7).16.2.11 Member AccessA member of a class X can be accessed by applying the . (dot) operator to an object of class X or byapplying the −> (arrow) operator to a pointer to an object of class X.

For example:struct X {void f();int m;};void user(X x, X∗ px){m = 1;// error: there is no m in scopex.m = 1;// OKx−>m = 1;// error: x is not a pointerpx−>m = 1;// OKpx.m = 1;// error: px is a pointer}Obviously, there is a bit of redundancy here: the compiler knows whether a name refers to an X orto an X∗, so a single operator would have been sufficient. However, a programmer might be confused, so from the first days of C the rule has been to use separate operators.From inside a class no operator is needed.

For example:void X::f(){m = 1;}// OK: ‘‘this->m = 1;’’ (§16.2.10)That is, an unqualified member name acts as if it had been prefixed by this−>. Note that a memberfunction can refer to the name of a member before it has been declared:struct X {int f() { return m; }int m;};// fine: return this X’s mIf we want to refer to a member in general, rather than to a member of a particular object, we qualify by the class name followed by ::. For example:Section 16.2.11Member Access467struct S {int m;int f();static int sm;};int X::f() { return m; }int X::sm {7};int (S::∗) pmf() {&S::f};// X’s f// X’s static member sm (§16.2.12)// X’s member fThat last construct (a pointer to member) is fairly rare and esoteric; see §20.6. I mention it here justto emphasize the generality of the rule for ::.16.2.12 [static] MembersThe convenience of a default value for Dates was bought at the cost of a significant hidden problem.Our Date class became dependent on the global variable today.

This Date class can be used only ina context in which today is defined and correctly used by every piece of code. This is the kind ofconstraint that causes a class to be useless outside the context in which it was first written. Usersget too many unpleasant surprises trying to use such context-dependent classes, and maintenancebecomes messy. Maybe ‘‘just one little global variable’’ isn’t too unmanageable, but that styleleads to code that is useless except to its original programmer. It should be avoided.Fortunately, we can get the convenience without the encumbrance of a publicly accessibleglobal variable. A variable that is part of a class, yet is not part of an object of that class, is called astatic member.

There is exactly one copy of a static member instead of one copy per object, as forordinary non-static members (§6.4.2). Similarly, a function that needs access to members of aclass, yet doesn’t need to be invoked for a particular object, is called a static member function.Here is a redesign that preserves the semantics of default constructor values for Date without theproblems stemming from reliance on a global:class Date {int d, m, y;static Date default_date;public:Date(int dd =0, int mm =0, int yy =0);// ...static void set_default(int dd, int mm, int yy); // set default_date to Date(dd,mm,yy)};We can now define the Date constructor to use default_date like this:Date::Date(int dd, int mm, int yy){d = dd ? dd : default_date.d;m = mm ? mm : default_date.m;y = yy ? yy : default_date.y;// ...

check that the Date is valid ...}468ClassesChapter 16Using set_default(), we can change the default date when appropriate. A static member can bereferred to like any other member. In addition, a static member can be referred to without mentioning an object. Instead, its name is qualified by the name of its class. For example:void f(){Date::set_default(4,5,1945);}// call Date’s static member set_default()If used, a static member – a function or data member – must be defined somewhere. The keywordstatic is not repeated in the definition of a static member.

For example:Date Date::default_date {16,12,1770};// definition of Date::default_datevoid Date::set_default(int d, int m, int y){default_date = {d,m,y};}// definition of Date::set_default// assign new value to default_dateNow, the default value is Beethoven’s birth date – until someone decides otherwise.Note that Date{} serves as a notation for the value of Date::default_date.

For example:Date copy_of_default_date = Date{};void f(Date);void g(){f(Date{});}Consequently, we don’t need a separate function for reading the default date. Furthermore, wherethe target type is unambiguously a Date, plain {} is sufficient. For example:void f1(Date);void f2(Date);void f2(int);void g(){f1({});f2({}):f2(Date{});// OK: equivalent to f1(Date{})// error: ambiguous: f2(int) or f2(Date)?// OKIn multi-threaded code, static data members require some kind of locking or access discipline toavoid race conditions (§5.3.4, §41.2.4). Since multi-threading is now very common, it is unfortunate that use of static data members was quite popular in older code. Older code tends to use staticmembers in ways that imply race conditions.Section 16.2.13Member Types46916.2.13 Member TypesTypes and type aliases can be members of a class.

For example:template<typename T>class Tree {using value_type = T;enum Policy { rb, splay, treeps };class Node {Node∗ right;Node∗ left;value_type value;public:void f(Tree∗);};Node∗ top;public:void g(const T&);// ...};// member alias// member enum// member classA member class (often called a nested class) can refer to types and static members of its enclosingclass. It can only refer to non-static members when it is given an object of the enclosing class torefer to. To avoid getting into the intricacies of binary trees, I use purely technical ‘‘f() andg()’’-style examples.A nested class has access to members of its enclosing class, even to private members (just as amember function has), but has no notion of a current object of the enclosing class.

For example:template<typename T>void Tree::Node::f(Tree∗ p){top = right;p−>top = right;value_type v = left−>value;}// error : no object of type Tree specified// OK// OK: value_type is not associated with an objectA class does not have any special access rights to the members of its nested class. For example:template<typename T>void Tree::g(Tree::Node∗ p){value_type val = right−>value;value_type v = p−>right−>value;p−>f(this);}// error : no object of type Tree::Node// error : Node::right is private// OKMember classes are more a notational convenience than a feature of fundamental importance. Onthe other hand, member aliases are important as the basis of generic programming techniques relying on associated types (§28.2.4, §33.1.3). Member enums are often an alternative to enum classeswhen it comes to avoiding polluting an enclosing scope with the names of enumerators (§8.4.1).470ClassesChapter 1616.3 Concrete ClassesThe previous section discussed bits and pieces of the design of a Date class in the context of introducing the basic language features for defining classes.

Here, I reverse the emphasis and discussthe design of a simple and efficient Date class and show how the language features support thisdesign.Small, heavily used abstractions are common in many applications. Examples are Latin characters, Chinese characters, integers, floating-point numbers, complex numbers, points, pointers, coordinates, transforms, (pointer,offset) pairs, dates, times, ranges, links, associations, nodes,(value,unit) pairs, disk locations, source code locations, currency values, lines, rectangles, scaledfixed-point numbers, numbers with fractions, character strings, vectors, and arrays.

Every application uses several of these. Often, a few of these simple concrete types are used heavily. A typicalapplication uses a few directly and many more indirectly from libraries.C++ directly supports a few of these abstractions as built-in types. However, most are not, andcannot be, directly supported by the language because there are too many of them.

Furthermore,the designer of a general-purpose programming language cannot foresee the detailed needs of everyapplication. Consequently, mechanisms must be provided for the user to define small concretetypes. Such types are called concrete types or concrete classes to distinguish them from abstractclasses (§20.4) and classes in class hierarchies (§20.3, §21.2).A class is called concrete (or a concrete class) if its representation is part of its definition. Thisdistinguishes it from abstract classes (§3.2.2, §20.4) which provide an interface to a variety ofimplementations. Having the representation available allows us:• To place objects on the stack, in statically allocated memory, and in other objects• To copy and move objects (§3.3, §17.5)• To refer directly to named objects (as opposed to accessing through pointers and references)This makes concrete classes simple to reason about and easy for the compiler to generate optimalcode for.

Thus, we prefer concrete classes for small, frequently used, and performance-criticaltypes, such as complex numbers (§5.6.2), smart pointers (§5.2.1), and containers (§4.4).It was an early explicit aim of C++ to support the definition and efficient use of such userdefined types very well. They are a foundation of elegant programming. As usual, the simple andmundane is statistically far more significant than the complicated and sophisticated. In this light,let us build a better Date class:namespace Chrono {enum class Month { jan=1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };class Date {public:// public interface:class Bad_date { }; // exception classexplicit Date(int dd ={}, Month mm ={}, int yy ={});// {} means ‘‘pick a default’’Section 16.3Concrete Classes471// nonmodifying functions for examining the Date:int day() const;Month month() const;int year() const;string string_rep() const;void char_rep(char s[], in max) const;// (modifying) functions for changing the Date:Date& add_year(int n);Date& add_month(int n);Date& add_day(int n);private:bool is_valid();int d, m, y;};bool is_date(int d, Month m, int y);bool is_leapyear(int y);// string representation// C-style string representation// add n years// add n months// add n days// check if this Date represents a date// representation// true for valid date// true if y is a leap yearbool operator==(const Date& a, const Date& b);bool operator!=(const Date& a, const Date& b);const Date& default_date();// the default dateostream& operator<<(ostream& os, const Date& d);istream& operator>>(istream& is, Date& d);} // Chrono// print d to os// read Date from is into dThis set of operations is fairly typical for a user-defined type:[1] A constructor specifying how objects/variables of the type are to be initialized (§16.2.5).[2] A set of functions allowing a user to examine a Date.

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

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

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

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