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

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

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

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

When g() calls use(), Vector_container’s operator[]() must be called. Toachieve this resolution, a Container object must contain information to allow it to select the rightfunction to call at run time. The usual implementation technique is for the compiler to convert thename of a virtual function into an index into a table of pointers to functions. That table is usually68A Tour of C++: Abstraction MechanismsChapter 3called the virtual function table or simply the vtbl.

Each class with virtual functions has its own vtblidentifying its virtual functions. This can be represented graphically like this:vtbl:Vector_container:Vector_container::operator[]()vVector_container::size()Vector_container::˜Vector_container()List_container:vtbl:List_container::operator[]()ldList_container::size()List_container::˜List_container()The functions in the vtbl allow the object to be used correctly even when the size of the object andthe layout of its data are unknown to the caller. The implementation of the caller needs only toknow the location of the pointer to the vtbl in a Container and the index used for each virtual function.

This virtual call mechanism can be made almost as efficient as the ‘‘normal function call’’mechanism (within 25%). Its space overhead is one pointer in each object of a class with virtualfunctions plus one vtbl for each such class.3.2.4 Class HierarchiesThe Container example is a very simple example of a class hierarchy. A class hierarchy is a setof classes ordered in a lattice created by derivation (e.g., : public). We use class hierarchies to represent concepts that have hierarchical relationships, such as ‘‘A fire engine is a kind of a truckwhich is a kind of a vehicle’’ and ‘‘A smiley face is a kind of a circle which is a kind of a shape.’’Huge hierarchies, with hundreds of classes, that are both deep and wide are common.

As a semirealistic classic example, let’s consider shapes on a screen:ShapeCircleTriangleSmileyThe arrows represent inheritance relationships. For example, class Circle is derived from classShape. To represent that simple diagram in code, we must first specify a class that defines the general properties of all shapes:Section 3.2.4Class Hierarchiesclass Shape {public:virtual Point center() const =0;virtual void move(Point to) =0;69// pure virtualvirtual void draw() const = 0;virtual void rotate(int angle) = 0;// draw on current "Canvas"virtual ˜Shape() {}// ...// destructor};Naturally, this interface is an abstract class: as far as representation is concerned, nothing (exceptthe location of the pointer to the vtbl) is common for every Shape. Given this definition, we canwrite general functions manipulating vectors of pointers to shapes:void rotate_all(vector<Shape∗>& v, int angle) // rotate v’s elements by angle degrees{for (auto p : v)p−>rotate(angle);}To define a particular shape, we must say that it is a(including its virtual functions):class Circle : public Shape {public:Circle(Point p, int rr);Shapeand specify its particular properties// constructorPoint center() const { return x; }void move(Point to) { x=to; }void draw() const;void rotate(int) {}private:Point x; // centerint r;// radius};// nice simple algorithmSo far, theShape and Circle example providesVector_container example, but we can build further:nothing new compared to theclass Smiley : public Circle { // use the circle as the base for a facepublic:Smiley(Point p, int r) : Circle{p,r}, mouth{nullptr} { }˜Smiley(){delete mouth;for (auto p : eyes) delete p;}Containerand70A Tour of C++: Abstraction MechanismsChapter 3void move(Point to);void draw() const;void rotate(int);void add_eye(Shape∗ s) { eyes.push_back(s); }void set_mouth(Shape∗ s);virtual void wink(int i);// wink eye number i// ...private:vector<Shape∗> eyes;Shape∗ mouth;};// usually two eyesThe push_back() member function adds its argument to the vector (here, eyes), increasing thatvector’s size by one.We can now define Smiley::draw() using calls to Smiley’s base and member draw()s:void Smiley::draw(){Circle::draw();for (auto p : eyes)p−>draw();mouth−>draw();}Note the way that Smiley keeps its eyes in a standard-library vector and deletes them in its destructor.

Shape’s destructor is virtual and Smiley’s destructor overrides it. A virtual destructor isessential for an abstract class because an object of a derived class is usually manipulated throughthe interface provided by its abstract base class. In particular, it may be deleted through a pointer toa base class. Then, the virtual function call mechanism ensures that the proper destructor is called.That destructor then implicitly invokes the destructors of its bases and members.In this simplified example, it is the programmer’s task to place the eyes and mouth appropriately within the circle representing the face.We can add data members, operations, or both as we define a new class by derivation.

Thisgives great flexibility with corresponding opportunities for confusion and poor design. See Chapter21. A class hierarchy offers two kinds of benefits:• Interface inheritance: An object of a derived class can be used wherever an object of a baseclass is required. That is, the base class acts as an interface for the derived class. The Container and Shape classes are examples. Such classes are often abstract classes.• Implementation inheritance: A base class provides functions or data that simplifies theimplementation of derived classes. Smiley’s uses of Circle’s constructor and of Circle::draw()are examples. Such base classes often have data members and constructors.Concrete classes – especially classes with small representations – are much like built-in types: wedefine them as local variables, access them using their names, copy them around, etc.

Classes inclass hierarchies are different: we tend to allocate them on the free store using new, and we accessSection 3.2.4Class Hierarchies71them through pointers or references. For example, consider a function that reads data describingshapes from an input stream and constructs the appropriate Shape objects:enum class Kind { circle, triangle, smiley };Shape∗ read_shape(istream& is) // read shape descriptions from input stream is{// ... read shape header from is and find its Kind k ...switch (k) {case Kind::circle:// read circle data {Point,int} into p and rreturn new Circle{p,r};case Kind::triangle:// read triangle data {Point,Point,Point} into p1, p2, and p3return new Triangle{p1,p2,p3};case Kind::smiley:// read smiley data {Point,int,Shape,Shape,Shape} into p, r, e1 ,e2, and mSmiley∗ ps = new Smiley{p,r};ps−>add_eye(e1);ps−>add_eye(e2);ps−>set_mouth(m);return ps;}}A program may use that shape reader like this:void user(){std::vector<Shape∗> v;while (cin)v.push_back(read_shape(cin));draw_all(v);// call draw() for each elementrotate_all(v,45);// call rotate(45) for each elementfor (auto p : v) delete p;// remember to delete elements}Obviously, the example is simplified – especially with respect to error handling – but it vividlyillustrates that user() has absolutely no idea of which kinds of shapes it manipulates.

The user()code can be compiled once and later used for new Shapes added to the program. Note that there areno pointers to the shapes outside user(), so user() is responsible for deallocating them. This is donewith the delete operator and relies critically on Shape’s virtual destructor. Because that destructor isvirtual, delete invokes the destructor for the most derived class.

This is crucial because a derivedclass may have acquired all kinds of resources (such as file handles, locks, and output streams) thatneed to be released. In this case, a Smiley deletes its eyes and mouth objects.Experienced programmers will notice that I left open two obvious opportunities for mistakes:• A user might fail to delete the pointer returned by read_shape().• The owner of a container of Shape pointers might not delete the objects pointed to.In that sense, functions returning a pointer to an object allocated on the free store are dangerous.72A Tour of C++: Abstraction MechanismsChapter 3One solution to both problems is to return a standard-library‘‘naked pointer’’ and store unique_ptrs in the container:unique_ptr(§5.2.1) rather than aunique_ptr<Shape> read_shape(istream& is) // read shape descriptions from input stream is{// read shape header from is and find its Kind kswitch (k) {case Kind::circle:// read circle data {Point,int} into p and rreturn unique_ptr<Shape>{new Circle{p,r}};// ...// §5.2.1}void user(){vector<unique_ptr<Shape>> v;while (cin)v.push_back(read_shape(cin));draw_all(v);// call draw() for each elementrotate_all(v,45);// call rotate(45) for each element} // all Shapes implicitly destroyedNow the object is owned by the unique_ptr which will delete the object when it is no longer needed,that is, when its unique_ptr goes out of scope.For the unique_ptr version of user() to work, we need versions of draw_all() and rotate_all() thataccept vector<unique_ptr<Shape>>s.

Writing many such _all() functions could become tedious, so§3.4.3 shows an alternative.3.3 Copy and MoveBy default, objects can be copied. This is true for objects of user-defined types as well as for builtin types. The default meaning of copy is memberwise copy: copy each member. For example,using complex from §3.2.1.1:void test(complex z1){complex z2 {z1};complex z3;z3 = z2;// ...}// copy initialization// copy assignmentNow z1, z2, and z3 have the same value because both the assignment and the initialization copiedboth members.When we design a class, we must always consider if and how an object might be copied. Forsimple concrete types, memberwise copy is often exactly the right semantics for copy. For somesophisticated concrete types, such as Vector, memberwise copy is not the right semantics for copy,and for abstract types it almost never is.Section 3.3.1Copying Containers733.3.1 Copying ContainersWhen a class is a resource handle, that is, it is responsible for an object accessed through a pointer,the default memberwise copy is typically a disaster.

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

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

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

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