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

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

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

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

In addition, it makes many sorts of code analysis feasible. Inparticular, it enables the compiler to detect illegal uses of objects that would otherwise be foundonly through exhaustive testing.The fundamental idea in defining a new type is to separate the incidental details of the implementation (e.g., the layout of the data used to store an object of the type) from the properties essential to the correct use of it (e.g., the complete list of functions that can access the data). Such a separation is best expressed by channeling all uses of the data structure and its internal housekeepingroutines through a specific interface.This chapter focuses on relatively simple ‘‘concrete’’ user-defined types that logically don’t differ much from built-in types:§16.2 Class Basics introduces the basic facilities for defining a class and its members.§16.3 Concrete Classes discusses the design of elegant and efficient concrete classes.The following chapters go into greater detail and presents abstract classes and class hierarchies:Chapter 17 Construction, Cleanup, Copy, and Move presents the variety of ways to controlinitialization of objects of a class, how to copy and move objects, and how toprovide ‘‘cleanup actions’’ to be performed when an object is destroyed (e.g.,goes out of scope).Chapter 18 Operator Overloading explains how to define unary and binary operators (suchas +, ∗, and !) for user-defined types and how to use them.Chapter 19 Special Operators considers how to define and use operators (such as [], (), −>,new) that are ‘‘special’’ in that they are commonly used in ways that differ fromarithmetic and logical operators.

In particular, this chapter shows how to definea string class.Chapter 20 Derived Classes introduces the basic language features supporting object-oriented programming. Base and derived classes, virtual functions, and access control are covered.Chapter 21 Class Hierarchies focuses on the use of base and derived classes to effectivelyorganize code around the notion of class hierarchies. Most of this chapter isdevoted to discussion of programming techniques, but technical aspects of multiple inheritance (classes with more than one base class) are also covered.Chapter 22 Run-Time Type Information describes the techniques for explicitly navigatingclass hierarchies.

In particular, the type conversion operations dynamic_cast andstatic_cast are presented, as is the operation for determining the type of an objectgiven one of its base classes (typeid).16.2 Class BasicsHere is a very brief summary of classes:• A class is a user-defined type.• A class consists of a set of members. The most common kinds of members are data members and member functions.• Member functions can define the meaning of initialization (creation), copy, move, andcleanup (destruction).Section 16.2Class Basics451••••Members are accessed using . (dot) for objects and −> (arrow) for pointers.Operators, such as +, !, and [], can be defined for a class.A class is a namespace containing its members.The public members provide the class’s interface and the private members provide implementation details.• A struct is a class where members are by default public.For example:class X {private:int m;public:X(int i =0) :m{i} { }int mf(int i){int old = m;m = i;return old;}// the representation (implementation) is private// the user interface is public// a constructor (initialize the data member m)// a member function// set a new value// return the old value};X var {7}; // a variable of type X, initialized to 7int user(X var, X∗ ptr){int x = var.mf(7);int y = ptr−>mf(9);int z = var.m;}// access using .

(dot)// access using -> (arrow)// error : cannot access private memberThe following sections expand on this and give rationale. The style is tutorial: a gradual development of ideas, with details postponed until later.16.2.1 Member FunctionsConsider implementing the concept of a date using a struct (§2.3.1, §8.2) to define the representation of a Date and a set of functions for manipulating variables of this type:struct Date {int d, m, y;};// representationvoid init_date(Date& d, int, int, int);void add_year(Date& d, int n);void add_month(Date& d, int n);void add_day(Date& d, int n);// initialize d// add n years to d// add n months to d// add n days to dThere is no explicit connection between the data type, Date, and these functions.

Such a connectioncan be established by declaring the functions as members:452ClassesChapter 16struct Date {int d, m, y;void init(int dd, int mm, int yy);void add_year(int n);void add_month(int n);void add_day(int n);// initialize// add n years// add n months// add n days};Functions declared within a class definition (a struct is a kind of class; §16.2.4) are called memberfunctions and can be invoked only for a specific variable of the appropriate type using the standardsyntax for structure member access (§8.2). For example:Date my_birthday;void f(){Date today;today.init(16,10,1996);my_birthday.init(30,12,1950);Date tomorrow = today;tomorrow.add_day(1);// ...}Because different structures can have member functions with the same name, we must specify thestructure name when defining a member function:void Date::init(int dd, int mm, int yy){d = dd;m = mm;y = yy;}In a member function, member names can be used without explicit reference to an object.

In thatcase, the name refers to that member of the object for which the function was invoked. For example, when Date::init() is invoked for today, m=mm assigns to today.m. On the other hand, whenDate::init() is invoked for my_birthday, m=mm assigns to my_birthday.m. A class member function‘‘knows’’ for which object it was invoked. But see §16.2.12 for the notion of a static member.16.2.2 Default CopyingBy default, objects can be copied. In particular, a class object can be initialized with a copy of anobject of its class. For example:Date d1 = my_birthday; // initialization by copyDate d2 {my_birthday}; // initialization by copySection 16.2.2Default Copying453By default, the copy of a class object is a copy of each member. If that default is not the behaviorwanted for a class X, a more appropriate behavior can be provided (§3.3, §17.5).Similarly, class objects can by default be copied by assignment.

For example:void f(Date& d){d = my_birthday;}Again, the default semantics is memberwise copy. If that is not the right choice for a class X, theuser can define an appropriate assignment operator (§3.3, §17.5).16.2.3 Access ControlThe declaration of Date in the previous subsection provides a set of functions for manipulating aDate. However, it does not specify that those functions should be the only ones to depend directlyon Date’s representation and the only ones to directly access objects of class Date. This restrictioncan be expressed by using a class instead of a struct:class Date {int d, m, y;public:void init(int dd, int mm, int yy);void add_year(int n);void add_month(int n);void add_day(int n);// initialize// add n years// add n months// add n days};The public label separates the class body into two parts. The names in the first, private, part can beused only by member functions.

The second, public, part constitutes the public interface to objectsof the class. A struct is simply a class whose members are public by default (§16.2.4); memberfunctions can be defined and used exactly as before. For example:void Date::add_year(int n){y += n;}However, nonmember functions are barred from using private members. For example:void timewarp(Date& d){d.y −= 200;// error: Date::y is private}The init() function is now essential because making the data private forces us to provide a way ofinitializing members. For example:Date dx;dx.m = 3;dx.init(25,3,2011);// error : m is private// OK454ClassesChapter 16There are several benefits to be obtained from restricting access to a data structure to an explicitlydeclared list of functions. For example, any error causing a Date to take on an illegal value (forexample, December 36, 2016) must be caused by code in a member function.

This implies that thefirst stage of debugging – localization – is completed before the program is even run. This is a special case of the general observation that any change to the behavior of the type Date can and mustbe effected by changes to its members. In particular, if we change the representation of a class, weneed only change the member functions to take advantage of the new representation. User codedirectly depends only on the public interface and need not be rewritten (although it may need to berecompiled). Another advantage is that a potential user need examine only the definitions of themember functions in order to learn to use a class. A more subtle, but most significant, advantage isthat focusing on the design of a good interface simply leads to better code because thoughts andtime otherwise devoted to debugging are expended on concerns related to proper use.The protection of private data relies on restriction of the use of the class member names.

It cantherefore be circumvented by address manipulation (§7.4.1) and explicit type conversion (§11.5).But this, of course, is cheating. C++ protects against accident rather than deliberate circumvention(fraud). Only hardware can offer perfect protection against malicious use of a general-purpose language, and even that is hard to do in realistic systems.16.2.4 class and structThe constructclass X { ...

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

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

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

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