ГОСУДАРСТВЕННЫЙ КОМИТЕТ РОССИЙСКОЙ ФЕДЕРАЦИИ ПО ВЫСШЕМУ ОБРАЗОВАНИЮ ────────────── ПЕНЗЕНСКИЙ ГОСУДАРСТВЕННЫЙ ТЕХНИЧЕСКИ...
7 downloads
183 Views
250KB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
ГОСУДАРСТВЕННЫЙ КОМИТЕТ РОССИЙСКОЙ ФЕДЕРАЦИИ ПО ВЫСШЕМУ ОБРАЗОВАНИЮ ────────────── ПЕНЗЕНСКИЙ ГОСУДАРСТВЕННЫЙ ТЕХНИЧЕСКИЙ УНИВЕРСИТЕТ ──────────────────────────────────────────────────
А.В.С и в о х и н
ОБЪЕКТНО-ОРИЕНТИРОВАННЫЙ ЯЗЫК ПРОГРАММИРОВАНИЯ С++ В ПРИМЕРАХ
Учебное пособие
ПЕНЗА 1994
УДК 681.3.06 С 34 Сивохин А.В. Объектно-ориентированный язык программирования С++ в примерах: Учеб. пособие/Под ред.профессора Б.Г.Хмелевского. - Пенза: Пенз. гос. техн. ун-т, 1994. -80 с.:3 ил., 3 табл., библиогр. 14 назв. Рассмотрены принципы объектно-ориентированного программирования и средства их реализации в языке С++.Дано обоснование иерархического подхода при разработке сложных программ, обеспечивающего адекватное и целостное представление в ЭВМ предметной области; на примерах показаны механизмы наследования и инкапсуляции данных вместе с обрабатывающими функциями, а также их использование для построения гибкого и надежного программного обеспечения; определены виды полиморфизма операций, функций и объектов, являющегося фундаментальным принципом технологии объектно-ориентированного программирования и представляющего наибольшую сложность в освоении технологии. Для серьезного использования на практике указанных возможностей языка С++ необходимо иметь полномасштабную справочную литературу,хорошие методические пособия и солидную программную поддержку для автоматизированного изучения языка на персональных ЭВМ,оснащенных компилятором С++.Недостаток или отсутствие всех этих материалов в настоящее время не позволяет эффективно организовать учебный процесс. Учебное пособие разработано на кафедре "Математическое обеспечение и применение ЭВМ" по дисциплине "Языки и системы представления знаний",ориентировано на использование пакета разработанных автором автоматизированных обучающих курсов и предназначено для студентов всех специальностей,которым в том или ином объме читаются основы технологии объектно-ориентированного программирования. Под редакцией профессора Б.Г.Хмелевского Р е ц е н з е н т ы : технический совет НПО "Рубин",г.Пенза; В.В.Пикулин,канд. техн. наук, доц. втуза. 2404010000 С------------------ Без объявл. 7К1(03)-94 С
Издательство Пензенского государственного университета.1994
В В Е Д Е Н И Е Язык программирования С++ является новой версией широко используемого на практике языка С,которая представляет собой существенное и вместе с тем почти строгое его расширение. Несмотря на свою молодость(первое полное описание С++ дано автором Бьярном Строуструпом в 1985 году[1]),он приобрел к настоящему времени значительное число сторонников как за рубежом,так и у нас в стране. Одно из принципиальных новшеств языка - это увеличение степени статического контроля типов используемых данных,производимого на стадии компиляции программы,что связано с требованиями создания надежного программного обеспечения на базе технологии абстракции данных. Именно слабость статического контроля языка С постоянно вызывала критику его оппонентов. Другое еще более важное новшество - это включение непосредственно в язык мощного аппарата для поддержания наиболее перспективной технологии - технологии объектно-ориентированного программирования: классы и объекты,иерархия структур,объединений и классов с различными механизмами наследования,инкапсуляция данных и обрабатывающих функций с несколькими уровнями доступа,полиморфизм операций,функций и объектов,обеспечивающий как статический,так и виртуальный методы доступа. Встроенный аппарат объектно-ориентированного программирования позволяет описывать сложные предметные области и создавать гибкие,легко адаптируемые к нуждам пользователя программные пакеты как системного,так и прикладного назначения. Наконец,третье новшество языка С++ - многочисленные улучшения языка С,порой даже вызывающие восторг у его пользователей: ссылки на типы,инициализация параметров значениями по умолчанию,параметризованные типы(шаблоны) составных объектов и функций,обработка исключительных ситуаций,новые директивы для препроцессирования. Поэтому не случайно многие сторонники языка используют при разработке программ только эти его возможности, т.е. работают всего лишь на "улучшенном" С,и лишь незначительная их часть пишут на действительно новом языке С++. 3
Для серьезного использования на практике новых по сравнению с С возможностей С++ необходимо,во-первых,технически освоить язык,а,во-вторых, глубоко разобраться в принципах объектно-ориентированного программирования и способах их реализации на языке С++. Все это требует и наличия полномасштабной справочной литературы,и хороших методических пособий,и наконец,солидной программной поддержки для автоматизированного обучения на персональных ЭВМ,оснащенных компилятором С++. Можно, конечно,достигнуть указанной цели,имея компьютер и компилятор С++,но это слишком дорогое удовольствие и доступно не каждому пользователю. Данное учебное пособие разрабатывалось с учетом указанных требований. Оно содержит разделы,где рассматриваются способы реализации принципов объектно-ориентированного программирования на языке С++:структуры с механизмами наследования,инкапсуляция данных и функций доступа к ним,полиморфизм операций,функций и объектов,а также дается фрагмент дидактического контекстно-свободного описания синтаксиса языка С++ с многочисленными примерами и краткими пояснениями. В приложении приведен текст обучающей программы для изучения аспектов объектноориентированного программирования. Пособие ориентируется на использование интеллектуальной обучающей системы,реализованной на персональных IBM-совместимых ЭВМ и имеющей большую и легко доступную информационную базу по языку С++,синтаксическую базу знаний,а также набор примеров для изучения семантики языка и контроля качества знаний. Заключение содержит перечень автоматизированных курсов,имеющихся в системе, и указания по их применению. Учебное пособие предназначено для самостоятельного изучения языка программирования С++ в учебных центрах и лабораториях, оснащенных персональными ЭВМ,и пригодно для различных категорий пользователей - от школьников и до преподавателей высших учебных заведений. 4
1.ОБЪЕКТНО-ОРИЕНТИРОВАННОЕ ПРОГРАММИРОВАНИЕ И ЕГО ПОДДЕРЖКА В С++ 1.1.Реальный мир и объекты Цель науки - выработка понятий и категорий о реальном мире,а также их теоретическая систематизация в виде генеалогических деревьев по тем или иным областям знаний.При этом единственная общая категория предметной области составляет корень дерева,от которого веером расходятся ветви к подчиненным категориям различного уровня вплоть до простых неделимых понятий.Такие деревья существуют для насекомых,рыб,млекопитающих,пресмыкающихся, растений,химических элементов,внутриатомных частиц,звездных галактик и т.д.На рис.1 приведен фрагмент генеалогического дерева для злаков. ┌───────┐ │ Злаки │ └───┬───┘ │ ┌────────────────────┬─┴──────────────────────┐ ┌────┴─────┐
┌────┴─────┐
┌─────────┴─────────┐
│ Зерновые │
│ Кормовые │
│ Сахарный тростник │
└────┬─────┘
└────┬─────┘
└───────────────────┘
│
└───────────────────┐
┌─┴──────────┬───────────┐
┌─────┴──────┐
┌──┴───┐
┌────┴────┐
┌──┴───┐
┌───┴────┐
┌───┴────┐
│ Рожь │
│ Пшеница │
│ Овес │
│ Мятлик │
│ Житняк │
└──────┘
└─────────┘
└──────┘
└────────┘
└────────┘
Рис.1.Фрагмент генеалогического дерева Категория "злаки" включает три подкатегории:"зерновые злаки","кормовые злаки" и "сахарный тростник".В свою очередь,две первые подкатегории имеют множество своих подкатегорий. Такой процесс классификации называется систематикой.Вопросы, какие задают себе ученые в этом процессе,таковы: 5
а)насколько новый объект похож на объекты какого-либо друго класса? б)чем он отличается от объектов этого класса? Процесс идентификации нового объекта начинается с корня генеалогического дерева и идет по ветвям до определения местоположения этого объекта в рассматриваемой классификации. Важно отметить,что как только свойство некоторой подкатегории задано,все подчиненные подкатегории обладают этим свойством.Это так называемый механизм наследования.Каждая отдельная подкатегория - это совокупность свойств и поведенческих функций,унаследованных от более общих подкатегорий, вместе с видовыми свойствами и поведенческими функциями, присущими только этой подкатегории и подкатегориям,ей подчиненным,причем в унаследованных поведенческих функциях возможны некоторые вариации. Иерархическое строение реального мира также объективно, как и сам реальный мир.Поэтому его любая модель,претендующая на адекватное описание,должна удовлетворять следующим необходимым условиям: а)целостное описание
свойств объектов и их поведенчес-
ких функций; б)иерархическая структура описания системы объектов с встроенным механизмом наследования свойств и функций; в)полиморфизм описательных средств для функций,обеспечивающий передачу действий вверх и вниз по иерархии объектов с реализацией этого действия способом,соответствующим каждому объекту в иерархии. Осмысление этих фактов в области программирования произошло в середине 80-х годов и привело к созданию нового стиля проектирования сложных программных систем,получившего название объектно-ориентированного программирования.Это - естественная эволюция более ранних подходов в проектировании языков программирования:оно более структурировано,чем предыдущие попытки в структурном программировании;оно более модульно и абстрактно,чем предыдущие попытки в абстрагировании данных и сокрытии деталей.К настоящему времени разработано несколько языков программирования,которые поддерживают этот 6
стиль.К их числу относится также язык С++.Объекты реального мира в этом языке представляются в зависимости от их сложности структурами,объединениями и классами. Эта концепция достаточно сложна,и даже опытным программистам требуется трехмесячная переподготовка для овладения новым стилем мышления и программирования.Итак,начнем с рассмотрения простых примеров. 1.2.Структуры
с механизмами наследования
Объект реального мира,будь то материальный предмет или физическое явление, характеризуется прежде всего некоторой совокупностью данных.Это напоминает структурный тип языка С++,который служит "оболочкой" или "капсулой" для соединения нескольких связанных между собой элементов данных под одним именем. Так, для позиции на экране можно задать следующий структурный тип: struct Location /*-позиция:
*/
{ int x,y;/*-координаты точки экрана;
*/
};/*-конец определения позиции;
*/
Здесь Location является типом структура;это - шаблон,который используется компилятором
для создания переменных типа струк-
тура.Переменная типа Location является отдельным экземпляром этого типа.В программе может быть определено любое число переменных типа Location,или,как принято называть в языке C++,любое число объектов типа Location: Location Loc0_0={0,0}; Location Loc9_9={9,9}; Location Loc1,Loc2,LocCent; Тип Location можно рассматривать двумя способами.Когда бывают нужны отдельные координаты х или у,то используют отдельные поля структуры Location и записывают,например,так: Loc0_0.x и Loc0_0.y.Если необходимо указать точку с координатами х и у, 7
которая определяет положение объекта на экране,то ссылаются на всю структуру Location. Предположим,что нам необходимо
высветить точку в позиции
на экране,описанной структурой Location.Определим тип typedef enum{false,true} Boolean;/*-булевский тип;
*/
и добавим к структуре Location поле,указывающее,светится ли точка в данной позиции.Новую структуру назовем Point: struct Point /*-точка на экране в графическом режиме: { int x,y
/*-координаты точки на экране;
Boolean Visible;/*-видимость точки на экране; };/*-конец определения точки;
*/ */ */ */
Язык С++ позволяет это записать и в другой форме: struct Point /*-точка на экране в графическом режиме: { Location Position;/*-позиция точки на экране; Boolean
*/ */
Visible ;/*-видимость точки на экране;
};/*-конец определения точки;
*/ */
Написанные структуры допустимы и в языке Турбо Си, и мы здесь не добавили ничего нового.Такой способ манипулирования данными затушевывает сущность рассматриваемых вещей.Дадим следующее определение точки:точка - это позиция на экране,работающем в графическом режиме,которая может светиться.А теперь воспользуемся возможностями языка C++ и построим структуры в соответствии с данным определением. В определении точки используется позиция этой точки на экране.В объектно-ориентированном программировании используется именно эта взаимосвязь.Поскольку все точки должны содержать позицию на экране,говорят,что тип Point - это тип,порожденный типом Location.Point наследует все,как в генеалогическом дереве,что имеет Location,и добавляет нечто новое к Point,чтобы сделать Point тем,чем оно должно быть-светящейся позицией. Процесс,посредством которого один тип наследует свойства другого типа,называется наследованием,а средства,с помощью 8
которых это достигается,механизмом наследования.Наследник называется порожденным типом;тип,от которого наследует порожденный тип,называется родительским,или базовым типом. В нашем примере два типа объектов следует теперь определить следующем образом: struct Location /*-позиция:
*/
{ int x,y; /*-координаты точки экрана;
*/
};/*-конец определения позиции;
*/
typedef enum{false,true} Boolean;/*-булевский тип;
*/
struct Point:/-точка на экране в графическом режиме;
*/
Location /*-позиция;
*/
{ Boolean Visible;/*-видимость точки на экране;
*/
};/*-конец определения точки на экране;
*/
Здесь двоеточие используется для указания наследования.При этом Location является родительским,или базовым типом,а Point - порожденным,или производным типом.Рассмотренный процесс может продолжаться бесконечно:можно задать наследников типа Point,наследников типа,порожденного от Point и т.д.Следует отметить,что большая часть применений объектно-ориентированного программирования состоит в построении этой иерархии объектов,выражающей семейное дерево объектов. Все типы,порожденные от Location,называются Location-порожденными типами,а тип Point - один из непосредственных наследников Location.В свою очередь,Location - непосредственный родитель для Point.Любой тип может иметь любое число непосредственных наследников,но только одного непосредственного предка,если не используется множественное наследование.При множественном наследовании производный тип имеет несколько базовых типов,имена которых задаются в его определении с помощью списка.Конечно,корневой тип не имеет предка. Производный тип Point используется в языке С++ так же,как и любой другой тип: 9
Point VarPoint={0,0,true};/*-переменная с инициализацией; */ Point& RefPoint=VarPoint; /*-ссылка на Point;
*/
Point* PtrPoint=new Point;/*-указатель на Point;
*/
tipedef struct Point* PointPtr;/*-производный от Point тип*/ PointPtr DynPoint;/*-требуется использование операторов
*/
/* new для размещения и delete для уда- */ /* ления структуры Point;
*/
Доступ к полям данных объектов производится обычным способом: cout