Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лекции АиП.doc
Скачиваний:
92
Добавлен:
15.11.2018
Размер:
668.67 Кб
Скачать
    1. Сложные классы

Создав сложный класс, можно объявить в нем ряд более простых классов. Например, можно объявить класс «колесо», класс «мотор» и класс «коробка передач», а затем объединить их в класс «автомобиль».

Рассмотрим следующий пример. Прямоугольник состоит из линий. Линия определяется двумя точками. Каждая точка определяется координатами x и y. В листинге 10.1 показано объявление класса Rectangle, содержащееся в файле Rectangle.h. Поскольку прямоугольник определяется четырьмя линиями, соединяющими четыре точки, и каждая точка определяется координатами на плоскости, сначала будет объявлен класс Point, предназначенный для хранения координат x и y каждой точки. Листинг 10.2 содержит реализацию обоих классов.

Листинг 10.1. Объявление класса Rectangle в файле Rectangle.h

#include <iostream>

class Point

{

public:

void SetX(int x) { itsX=x; }

void SetY(int y) { itsY=y; }

int GetX() const { return itsX; }

int GetY() const { return itsY; }

private:

int itsX;

int itsY;

};

class Rectangle

{

public:

Rectangle(int top, int left, int bottom, int right);

~Rectangle() { }

int GetTop() const { return itsTop; }

int GetLeft() const { return itsLeft; }

int GetBottom() const { return itsBottom; }

int GetRight() const { return itsRight; }

Point GetUpperLeft() const {return itsUpperLeft; }

Point GetLowerLeft() const {return itsLowerLeft; }

Point GetUpperRight() const {return itsUpperRight; }

Point GetLowerRight() const {return itsLowerRight; }

void SetUpperLeft(Point Location)

{ itsUpperLeft=Location; }

void SetLowerLeft(Point Location)

{ itsLowerLeft=Location; }

void SetUpperRight(Point Location)

{ itsUpperRight=Location; }

void SetLowerRight(Point Location)

{ itsLowerRight=Location; }

void SetTop(int top) { itsTop=top;}

void SetLeft(int left) { itsLeft=left;}

void SetBottom(int bottom) { itsBottom=bottom;}

void SetRight(int right) { itsRight=right;}

int GetArea() const;

private:

Point itsUpperLeft;

Point itsUpperRight;

Point itsLowerLeft;

Point itsLowerRight;

int itsTop;

int itsLeft;

int itsBottom;

int itsRight;

};

Листинг 10.2. Реализация класса Rectangle в файле Rectangle.cpp

#include "Rectangle.h"

Rectangle::Rectangle(int top, int left, int bottom, int right)

{

itsTop=top;

itsLeft=left;

itsBottom=bottom;

itsRight=right;

itsUpperLeft.SetX(left);

itsUpperLeft.SetY(top);

itsUpperRight.SetX(right);

itsUpperRight.SetY(top);

itsLowerLeft.SetX(left);

itsLowerLeft.SetY(bottom);

itsLowerRight.SetX(right);

itsLowerRight.SetY(bottom);

}

/*Найти по точкам ширину и высоту, а затем,

перемножив их, вычислить площадь прямоугольника*/

int Rectangle::GetArea() const

{

int Width=itsRight-itsLeft;

int Height=itsTop-itsBottom;

return (Width*Height);

}

int main()

{

//Инициализировать объект MyRectangle класса Rectangle

Rectangle MyRectangle(100, 20, 50, 80);

int Area=MyRectangle.GetArea();

std::cout<<"Area: "<<Area<<std::endl;

std::cout<<"Upper Left X Coordinate: ";

std::cout<<MyRectangle.GetUpperLeft().GetX();

char Res;

std::cin>>Res;

return 0;

}