1 of 29

Объектно-ориентированное программирование

основные понятия:

инкапсуляция

абстрагирование

наследование

полиморфизм

сетевой адрес этой презентации

clck.ru/9uu6E

2 of 29

Инструментарий ООП

Вспомогательные и справочные материалы по С++ clck.ru/9aZFe

Скачать:

0. С# Express 2008 (~500Мб): скачать setup

1. Dev_C++ Version 5.8.0 (45 Мб): скачать setup �  2. Настройка кириллицы: скачать папку с настройками �  3. Справочник по С++: скачать справочник

Текст в справочнике может не отображаться в современных ОС – обратитесь на официальный сайт майкрософт за обновлением : Программа "Справка Windows" (WinHlp32.exe)

4. ГОСТ 19.701-90. Схемы алгоритмов, программ, данных и систем. смотреть документ

3 of 29

Литература

Основная:

Дополнительная:

4 of 29

Технология ООП

структуры, классы и объекты

new

перегрузка

конструктор/деструктор

инкапсуляция

static

абстрагирование

private

protected модификаторы доступа

public

наследование

полиморфизм (статический и динамический)

virtual

5 of 29

Настройки

6 of 29

шаблон минимальной программы

#include <iostream>

using namespace std;

int main()

{

cin >> x;

cout << x+2 << endl;

return 0;

}

переопределение типа

typedef unsigned long long ULL;

7 of 29

пример с русификацией

#include <iostream>

#include <windows.h>

using namespace std;

int main()

{

SetConsoleCP(1251);

SetConsoleOutputCP(1251);

string s = "Потоп";

for(int i=0; i<s.length(); i++)

cout << s[i] << endl;

}

8 of 29

перегрузка функций

#include <iostream>

using namespace std;

int sum(int x)

{

return x+1;

}

int sum(int x, int step)

{

return x+step;

}

void inc(int &x)

{

x++;

}

void inc(int &x, int step)

{

x += step;

}

int main()

{

int a = 0, b = 0;

cout << sum(a) << endl;

cout << sum(b,3) << endl;

inc(a); cout << a << endl;

inc(b,5); cout << b << endl;

return 0;

}

9 of 29

перегрузка функций

способ

многовариантной реализации функции

в зависимости от типа данных аргументов

10 of 29

Заголовочный файл / свой

#include <iostream>

#include <string>

#include <algorithm>

#include <fstream>

#include <locale>

#include <vector>

#include <windows.h>

#include <stdio.h>

using namespace std;

inline void start()

{

SetConsoleCP(1251);

SetConsoleOutputCP(1251);

system("cls");

}

inline void start(char b[3])

{

SetConsoleCP(1251);

SetConsoleOutputCP(1251);

char clr[9] = "color ";

strncat(clr,b,2);

system(clr);

system("cls");

}

#include "start"

int main()

{

start("1E");

string name;

cout << "Ваше имя ? - ";

cin >> name;

cout << "Привет - " << name;

cout << endl;

system("pause");

return 0;

}

такие скобки < > для заголовочных файлов от разработчика

такие скобки " " для заголовочных файлов от программиста

11 of 29

class my

{

public:

static int a;

};

int my::a;

int main()

{

cout<< my::a <<'\n';

my::a=10;

cout<< my::a <<'\n';

my Ob;

cout<< Ob.a <<'\n';

Ob.a=5;

cout<< my::a;

return 0;

}

class my

{

public:

static int x;

};

int my::x;

int main()

{

const int count = 5;

my ob[count];

for (int i=0;i<count;i++)

ob[i].x = i;

for (int i=0;i<count;i++)

cout << ob[i].x << "\t";

cout << endl;

}

static

массив объектов

12 of 29

класс

декларированная совокупность

полей данных и

функций для работы с ними

объект - это экземпляр класса

13 of 29

абстрагирование

предоставление интерфейса

для работы с данными класса

сокрытие некоторых полей и функций

класса

инкапсуляция

14 of 29

class liver

{

protected:

int age;

};

class human: public liver

{

public:

string name1, name2, name3;

string fio = "";

void setage(int d)

{ // установить возраст

if (d>=0 && d<=120)

age = d;

else cerr << "ERROR";

}

string getfio()

{ // получить инициалы

fio = fio + name1[0] + name2[0] + name3[0];

return fio;

}

};

пример реализации

C++

15 of 29

#include <iostream>

using namespace std;

class class_0

{

public:

class_0() {cout<<"0+"<<endl;}

~class_0() {cout<<"0-"<<endl;}

};

class class_1: class_0

{

public:

class_1() {cout<<"1+"<<endl;}

~class_1() {cout<<"1-"<<endl;}

};

int main()

{

class_1 e;

}

конструкторы и деструкторы

C++

16 of 29

конструктор

особая функция

для инициализации объекта

объект - это экземпляр класса

17 of 29

пример new

int main()

{

my t;

t.b = 4.05;

my* p = new my;

p->b=4.05;

my* w = new my(1,4.05,1);

t.printroot();

p->printroot();

w->printroot();

cout << w->disc();

}

class my

{

public:

double a, b, c;

my()

{

a = 1; b = 2; c = 1;

}

my(double aa, double bb, double cc)

{

a = aa; b = bb; c = cc;

}

double disc()

{

return b*b - 4*a*c;

}

void printroot()

{

double d = disc();

if (d>0)

{

cout << ( -b+sqrt(d) ) / 2 / a << endl;

cout << ( -b-sqrt(d) ) / 2 / a << endl;

}

if (d==0)

{

cout << -b / 2 / a << endl;

}

if (d<0)

{

cout << "no" << endl;

}

}

};

18 of 29

class myr

{

private:

double d;

public:

double a,b,c;

myr()

{

a = 1; b = 2; c = 1; d=0;

}

myr(double aa, double bb, double cc)

{

a = aa; b = bb; c = cc;

d = b*b - 4*a*c;

}

void getroot()

{

if (d>0)

{

cout << 2 << " - root" << endl;

cout << (-b+sqrt(d))/2/ a << endl;

cout << (-b-sqrt(d))/2/ a << endl;

}

if (d==0)

{

cout << 1 << " - root" << endl;

cout << -b / 2 / a << endl;

}

if (d<0)

{

cout << 0 << " - root" << endl;

}

}

};

пример класса C++

int main(int argc, char* argv[])

{

system("cls");

if (argc!=4)

{

myr tt;

tt.getroot();

}

else

{

myr tt(

atof(argv[1]),

atof(argv[2]),

atof(argv[3]));

tt.getroot();

}

system("pause");

return 0;

}

19 of 29

запуск консольной программы с аргументами

private void button1_Click(object sender, EventArgs e)

{

string exe = textBox1.Text;

string arg =

textBox2.Text + " " + textBox3.Text + " " + textBox4.Text;

System.Diagnostics.Process.Start(exe, arg);

}

procedure TForm1.button1Click(Sender: TObject);

var ToRun:string;

begin

ToRun:=edt1.Text+' '+edt2.Text+' '+edt3.Text+' '+edt4.Text;

winexec(PChar(ToRun), SW_SHOW);

end;

Delphi

C#

консоль

20 of 29

namespace WindowsFormsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

public class my

{

private

int a;

public my()

{

a = 0;

}

public my(int x)

{

a = x;

}

public void Seta(int x)

{

a = x;

}

public int geta()

{

return a + 1;

}

};

//////////////////////

}

}

пример класса C#

private void button1_Click(object sender, EventArgs e)

{

my t = new my();

textBox2.Text = Convert.ToString(t.geta());

}

private void button2_Click(object sender, EventArgs e)

{

my t = new my();

t.Seta(Convert.ToInt32(textBox3.Text));

textBox3.Text = Convert.ToString(t.geta());

}

21 of 29

public class sr

{

private double d = 0;

private void disk()

{

d = b * b - 4 * a * c;

if (d > 0)

{

x1 = (-b + Math.Sqrt(d)) / 2 / a;

x2 = (-b - Math.Sqrt(d)) / 2 / a;

count = 2;

}

if (d == 0)

{

x1 = -b / 2 / a;

x2 = 0;

count = 1;

}

if (d < 0)

{

x1 = 0;

x2 = 0;

count = 0;

}

}

public double a, b, c;

public double x1, x2;

public int count;

public sr()

{

a = 0; b = 0; c = 0; x1 = 0; x2 = 0; count = 0;

disk();

}

public sr(double aa, double bb, double cc)

{

a = aa; b = bb; c = cc; x1 = 0; x2 = 0; count = 0;

disk();

}

};

пример класса C#

private void Form1_MouseClick(object sender, MouseEventArgs e)

{

sr t = new sr(

Convert.ToDouble(textBox1.Text),

Convert.ToDouble(textBox2.Text),

Convert.ToDouble(textBox3.Text));

textBox4.Text = Convert.ToString(t.count);

textBox5.Text = Convert.ToString(t.x1.ToString("#0.000#"));

textBox6.Text = Convert.ToString(t.x2.ToString("#0.000#"));

}

22 of 29

struct sqroot

{

double x1;

double x2;

int e;

};

struct koef

{

double a;

double b;

double c;

};

int main()

{

start('2','E');

koef z; z.a = 1.0; z.b = -2.5 ; z.c = -7.02;

sqroot f = fff(z);

cout << "корней - " << f.e << "\n" << f.x1 << "\n" << f.x2 << endl;

system("pause");

return 0;

}

sqroot fff(koef z)

{

double d = 0; sqroot j;

d = pow(z.b,2) - 4*z.a*z.c;

if (d>0)

{

j.x1 = -z.b + sqrt(d) / 2 / z.a;

j.x2 = -z.b - sqrt(d) / 2 / z.a;

j.e = 2;

}

if (d=0)

{

j.x1 = -z.b / 2 / z.a;

j.x2 = -z.b / 2 / z.a;

j.e = 1;

}

if (d>0)

{

j.x1 = 0;

j.x2 = 0;

j.e = 0;

}

return j;

}

структуры

23 of 29

class animal

{

bool sex;

public:

int age;

animal()

{

sex = true;

age = 0;

}

void setsex(bool e)

{

sex = e;

}

string getsex ()

{

return sex? "муж": "жен";

}

};

классы

struct sqroot

{

double x1;

double x2;

int e;

};

конструктор

абстрагирование

методы

24 of 29

class my

{

protected:

int age;

public:

my() {age=0;}

//virtual

int getage()

{return age;}

};

class my1: public my

{

public:

int getage()

{return age+1;}

};

class my2: public my

{

public:

int getage()

{return age+2;}

};

полиморфизм

int print(my &id)

{

return id.getage();

}

int main()

{

my Ob; cout << Ob.getage();

my1 Ob1; cout << Ob1.getage();

my2 Ob2; cout << Ob2.getage();

cout << endl;

cout << print(Ob);

cout << print(Ob1);

cout << print(Ob2);

}

статический

012

000

25 of 29

class my

{

protected:

int age;

public:

my() {age=0;}

virtual

int getage()

{return age;}

};

class my1: public my

{

public:

int getage()

{return age+1;}

};

class my2: public my

{

public:

int getage()

{return age+2;}

};

полиморфизм

int print(my &id)

{

return id.getage();

}

int main()

{

my Ob; cout << Ob.getage();

my1 Ob1; cout << Ob1.getage();

my2 Ob2; cout << Ob2.getage();

cout << endl;

cout << print(Ob);

cout << print(Ob1);

cout << print(Ob2);

}

динамический

012

012

26 of 29

полиморфизм

интерфейс доступа один

реализация зависит от типа объекта

27 of 29

class animal

{

private:

bool sex;

public:

int age;

animal()

{

sex = true;

age = 0;

}

void setsex(bool e)

{

sex = e;

}

void setsex (string hsex)

{

sex = (hsex[0]=='м' || hsex[0]=='М' || hsex[0]=='m' || hsex[0]=='M');

}

void setsex (char hsex)

{

sex = (hsex=='ж' || hsex=='Ж' || hsex=='m' || hsex=='M');

}

string getsex ()

{

return sex? "муж": "жен";

}

bool getsexbool ()

{

return sex;

}

void setage(int newage)

{

age = newage;

}

virtual int getage()

{

return age;

}

};

классы

перегрузка

виртуальность

28 of 29

namespace WFA_class

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

public class Base

{

private int _age;

public int age

{

get {return _age;}

set {_age = value;}

}

public bool sex

{ get; set; }

}

Base obj1 = new Base();

private void button1_Click(object sender, EventArgs e)

{

obj1.age = Convert.ToInt32(textBox4.Text);

obj1.sex = checkBox1.Checked;

}

private void button2_Click(object sender, EventArgs e)

{

if (obj1.sex)

textBox5.Text = Convert.ToString(obj1.age);

else

textBox5.Text = Convert.ToString(obj1.age - 5);

}

}

}

Пример C# приложение с формой

29 of 29

Техническое задание

  • создать иерархию классов (UML и C++)
  • базовый класс:

Живое

(атрибуты: возраст/скрытый)

(методы: установить возраст, получить возраст)

  • производный (от Живое) класс - 1 уровень:

Человек

(атрибуты: Фамилия, Имя, Отчество, Пол)

(методы: получить инициалы, получить пол в виде слова,

получить возраст - зависит от пола)

  • производный (от Человек) класс - 2 уровень:

Работник

(атрибуты: отдел, телефон, стаж, зарплата)

(методы: установить ставку зарплаты,

получить зарплату - зависит от стажа)

  • производный (от Живое) класс 1 уровень:

Ork_B

(методы: получить возраст - возвращает как двоичное число,

установить возраст - принимает как десятичное число)

  • производный (от Живое) класс 1 уровень:

Ork_D

(методы: установить возраст - принимает как двоичное число,

получить возраст - возвращает как десятичное)

3

5

4