Кафедра вычислительной математики и программирования
Лабораторные работы 1 — 8 по курсу СППО:
основы программирования на языке С++
(__________Волков В.А. в1_________)
Основная папка:
1.АГРЕГАЦИЯ ПО ССЫЛКЕ (lab1.cpp, lab1.exe______________)
имена файлов
2.АГРЕГАЦИЯ ПО ЗНАЧЕНИЮ И ВЛОЖЕНИЕМ (lab1_vlog.cpp,lab1_znach.cpp,*.exe)
3.ПРИНЦИП ПОДСТАНОВКИ (lab2_podst.cpp, lab2_podst.exe___)
4.НАСЛЕДОВАНИЕ: РАСШИРЕНИЕ, СПЕЦИФИКАЦИЯ, СПЕЦИАЛИЗАЦИЯ, КОНСТРУИРОВАНИЕ, КОМБИНИРОВАНИЕ (lab2_nasl.cpp, lab2_comb.cpp,*.exe)
5.НАСЛЕДОВАНИЕ: КОМБИНИРОВАНИЕ ЧЕРЕЗ ОБЩИХ ПРЕДКОВ (lab2_commnasl.cpp, *.exe________)
6.АССОЦИАЦИЯ (lab3.cpp,lab3_1-n.cpp, *.exe______)
7.ИСПОЛЬЗОВАНИЕ (lab4.cpp,lab4_obsh.cpp,*.exe_____)
8.КОНКРЕТИЗАЦИЯ (lab5_funk.cpp,lab5_class.cpp,*.exe_)
Работу выполнил:
08-202 Волков В ________ ________
Группа ФИО: Подпись Вариант
Руководитель: ________/Семенов А.С./
Подпись:
1.АГРЕГАЦИЯ ПО ССЫЛКЕ (lab1.cpp, lab1.exe______________)
имена файлов
2.АГРЕГАЦИЯ ПО ЗНАЧЕНИЮ И ВЛОЖЕНИЕМ (lab1_vlog.cpp,lab1_znach.cpp,*.exe)
3.ПРИНЦИП ПОДСТАНОВКИ (lab2_podst.cpp, lab2_podst.exe___)
4.НАСЛЕДОВАНИЕ: РАСШИРЕНИЕ, СПЕЦИФИКАЦИЯ, СПЕЦИАЛИЗАЦИЯ, КОНСТРУИРОВАНИЕ, КОМБИНИРОВАНИЕ (lab2_nasl.cpp, lab2_comb.cpp,*.exe)
5.НАСЛЕДОВАНИЕ: КОМБИНИРОВАНИЕ ЧЕРЕЗ ОБЩИХ ПРЕДКОВ (lab2_commnasl.cpp, *.exe________)
6.АССОЦИАЦИЯ (lab3.cpp,lab3_1-n.cpp, *.exe______)
7.ИСПОЛЬЗОВАНИЕ (lab4.cpp,lab4_obsh.cpp,*.exe_____)
8.КОНКРЕТИЗАЦИЯ (lab5_funk.cpp,lab5_class.cpp,*.exe_)
1.АГРЕГАЦИЯ ПО ССЫЛКЕ
|
|
|
// lab1.cpp: определяет точку входа для консольного приложения.
#include "stdafx.h"
#include "conio.h"
#include <iostream>
using namespace std;
class E {
public:
E() {e = 0;}
int e;
void me() {
e += 1;
cout<<"e = " << e << endl;
};
};
class F {
public:
F() {f = 0;}
int f;
void mf() {
int f = 0;
f += 1;
cout<<"f = " << f << endl;
};
};
class D {
public:
D() {int d = 0;};
void md() {
int d=0;
d += 1;
cout <<"d = "<< d << endl;
};
};
class B {
private:
D *d;
public:
B() {}//конструктор, без параметров
void link (D &d) { this -> d = &d;}
D *mbd() {return d;}
};
class C {
private:
E *e;
F *f;
public:
C() {}
void link (E &e) { this->e = &e;}
E *mce() {return e;}
void link (F &f) { this->f = &f;}
F *mcf() {return f;}
};
class A {
public:
A() {}
void link (B &b) { this -> b = &b;}//B &b указатель
void link (C &c) { this -> c = &c;}
C *mac() { return c;}
B *mab() { return b;}
private:
B *b;
C *c;
};
int main() {
A a;B b;C c;D d;E e;F f;
a.link(b);a.link(c);
b.link(d);
c.link(e);c.link(f);
a.mab() -> mbd() -> md();
a.mac() -> mce() -> me();
a.mac() -> mcf() -> mf();
_getche();
return 0;
}
2.АГРЕГАЦИЯ ПО ЗНАЧЕНИЮ
|
|
|
|
// lab1_znach.cpp: определяет точку входа для консольного приложения.
#include "stdafx.h"
#include "conio.h"
#include <iostream>
using namespace std;
class A{
public:
class B{
public:
class D{
public:
D() {d = 0;}
int d;
void md() {
d += 1;
cout << "d = " << d << endl;
}
};
B() {}
D* mbd() {return &d;}
private:
D d;
};
class C{
public:
class F{
public:
F() {f = 0;}
int f;
void mf() {
f += 1;
cout << "f = " << f << endl;
}
};
class E{
public:
E() {e = 0;}
int e;
void me() {
e += 1;
cout << "e = " << e << endl;
}
};
C() {}
F* mcf() {return &f;}
E* mce() {return &e;}
private:
F f;
E e;
};
A() {}
B* mab() {return &b;}
C* mac() {return &c;}
private:
B b;
C c;
};
int main() {
A a;
a.mac()->mcf()->mf();
a.mac()->mce()->me();
a.mab()->mbd()->md();
_getche();
return 0;
}
2.АГРЕГАЦИЯ ВЛОЖЕНИЕМ
// lab1_vlog.cpp: определяет точку входа для консольного приложения.
#include "stdafx.h"
#include "conio.h"
#include <iostream>
using namespace std;
class A {
public:
class B {
public:
class D {
public:
D() {d = 0;}
int d;
void md() {
d += 1;
cout << "d = " << d << endl;
}
};
B() {}
D* mbd() {return &d;}
private:
D d;
};
class C {
public:
class F {
public:
F() {f = 0;}
int f;
void mf() {
f += 1;
cout << "f = " << f << endl;
}
};
class E {
public:
E() {e = 0;}
int e;
void me() {
e += 1;
cout << "e = " << e << endl;
}
};
C() {}
F* mcf() {return &f;}
E* mce() {return &e;}
private:
F f;
E e;
};
A() {}
B* mab() {return &b;}
C* mac() {return &c;}
private:
B b;
C c;
};
int main(int argc, char* argv[])
{
setlocale (LC_ALL,"Russian");
cout << "агрегация вложением\n";
A a;
a.mac()->mcf()->mf();
a.mac()->mce()->me();
a.mab()->mbd()->md();
_getche();
return 0;
}
3.ПРИНЦИП ПОДСТАНОВКИ
// lab2_podst.cpp: определяет точку входа для консольного приложения.
#include "stdafx.h"
#include <iostream>
#include "conio.h"
#include <fstream>
#include "stdio.h"
using namespace std;
class A {
public:
A() {a = 0; cout << "constr A" << a << endl;}
//A супер класс, В под класс, вместо объекта супер класса А
//можно подставить объект подкласса В, также В супер класс для С.
virtual ~A() { cout << "distr A" << endl;}
virtual int getA() {return a=0;}
protected:
int a;
};
class B:
public A {
public:
B() {a = 1; cout << "constr B" << a << endl;}
~B() { cout << "distr B" << endl;}
int getA() {return a;}
};
class D:
public B {
public:
D() {a = 2; cout << "constr D" << a << endl;}
~D() { cout << "distr D" << endl;}
int Ma() {return a;}
};
int main()
{
char ch;
cout << "hi" << endl;
A *a = NULL;
a = new A;
cout << a->getA() << endl;
delete a;//удаление объекта класса А по указателю а
cout << "step 1" << endl;
a = new B;//реализация подстановки
cout << a->getA() << endl;
delete a;
cout << "step2" << endl;
a = new D;//взяли указатель, вместо объекта супер класа подставляется объект подкласса
cout << a->getA() << endl;//берём объект D по указателю, вызываем супер ф-ю класса А, она замещается ф-ей класса D
if(dynamic_cast <D*>(a)!= NULL)
{
cout << "yes D" << endl;
}
delete a;
cout << "step3" << endl;
{
D d;
}
_getche();
return 0;
}
4.1 НАСЛЕДОВАНИЕ: РАСШИРЕНИЕ, СПЕЦИФИКАЦИЯ, СПЕЦИАЛИЗАЦИЯ, КОНСТРУИРОВАНИЕ(граф изменён)
|
|
// lab2_nasl.cpp
#include "stdafx.h"
#include <iostream>
#include <clocale>
using namespace std;
class A {
protected:
int a;
public:
A():a(10) {}
virtual int fa() {return a;}
int fA() {return -a;}
};
class B:
public A {
public:
int fa() {return a + 1;} //переопределение fa()
};
class J:
public A { //расширение
protected:
int j;
public:
int fa() {return a*a;} //изменение аргументов (перегрузка)
int fj() {return j;} //изменение пространства имен
};
class C:
public A { //конструирование
protected:
int c;
public:
int fA(int i) {return i + a;}
virtual int fc() = 0;
int fC() {return c;}
};
class F:
public C { //спецификация
public:
int fc() {return a + 1000;}
};
class E:
public C { //спецификация
public:
int fc() {return a + 1001;}
};
class D:
private B { //конструирование (закрытое наследование)
public:
int fa() {return B::fa()*B::fa();} //конструирование
};
int main(int argc, char* argv[])
{
setlocale (LC_ALL,"Russian");
A *a = NULL;
cout << "=========== специализация ===========\n";
a = new A;
cout << a->fa() << endl;
delete a;
a = new B;
cout << a->fa() << endl; // принцип подстановки выполняется полностью
delete a;
cout << "=========== расширение ===========\n";
a = new A;
cout << a->fa() << endl;
delete a;
a = new J;
cout << a->fa() << endl; // принцип подстановки выполняется
//cout << a->fj() << endl; // частично
cout << "=========== спецификация ===========\n";
C *c = NULL;
//c = new C; //C - абстрактный класс
c = new F;
cout << c->fc() << endl;
c = new E;
cout << c->fc() << endl;
cout << "======= конструирование (закрытое насл) =======\n";
B *b = NULL;
b = new B;
cout << b->fa() << endl;
//b = new D; //принцип подстановки не выполняется
D d;
cout << b->fa() << endl;
return 0;
}
4.2 НАСЛЕДОВАНИЕ: КОМБИНИРОВАНИЕ(граф изменём)
// lab2_comb.cpp:
#include "stdafx.h"
#include "conio.h"
#include <iostream>
#include <locale>
using namespace std;
class E {
protected:
int e;
public:
E():e(2) {}
int fe() {return e;}
};
class F {
protected:
int f;
public:
F():f(3) {}
int ff() {return f;}
};
class C:public E, protected F {
protected:
int c; // расширение по данным (для всех)
public:
C():c(5) {}
int fc() {return f*e;} // конструирование для (B->E и B->D)
};
class D {
protected:
int d;
public:
D():d(4) {}
virtual int fd() {return d;}
};
class B:public D {
protected:
int b;
public:
int fd() {return d*d;} // специализация (для C->F)
};
class J {
public:
virtual int fj() = 0;
};
class A: public J, public B, private C {
protected:
int a;
public:
int fd() {return d*d*d;} // специализация (для A->B)
// конструирование (для A->C и A->E)
int fj() {return a*fc()*B::fd();} // спецификация (для A->E)
// конструирование (для A->C и A->E)
// расширение по методам (для A->B)
};
int main(int argc, char* argv[])
{
setlocale (LC_ALL,"Russian");
//принцип подстановки выполняется для B->D:
D *d = NULL;
cout << "Принцип подстановки для B->D:\n";
d = new D;
cout << d->fd() << endl;
d = new B;
cout << d->fd() << endl;
//принцип подстановки частично выполняется для A->B:
B* b = NULL;
cout << "Принцип подстановки для A->B:\n";
b = new B;
cout << b->fd() << endl;
b = new A;
cout << b->fd() << endl;
// по остальным веткам принцип подстановки не выполняется
_getche();
return 0;
}
5. НАСЛЕДОВАНИЕ: КОМБИНИРОВАНИЕ ЧЕРЕЗ ОБЩИХ ПРЕДКОВ
// lab2_commnasl.cpp:
#include "stdafx.h"
#include <iostream>
using namespace std;
class A {
public:
A() {a = 0;cout << "A() a = " << a << endl;}
A(int a) {this->a = a; cout << "A(int a) a = " << a << endl;}
virtual ~A() {}
virtual int fa() {return a;}
private:
int a;
};
class C:public virtual A {
public:
C() {c = 2; cout << "C() c = " << c << endl;}
C(int a):A(a) {c = 2; cout << "C(int a) c = " << c << endl;}
int fc() {return c;}
int fC() {return c + A::fa();}
private:
int c;
};
class B:virtual A {
public:
B() {b = 1; cout << "B() b = " << b << endl;}
B(int a):A(a) {b = 1; cout << "B(int a) b = " << b << endl;}
int fb() {return b;}
int fB() {return b + A::fa();}
private:
int b;
};
class E:public B,public C {
public:
E():C(),B() {e = 6; cout << "E() e = " << e << endl;}
E(int a):C(),A(a) {e = 6; cout << "E(int a0) e = " << e << endl;}
E(int a0, int a1):B(),A(a0+a1),C() {e = 6; cout << "E(int a0, int a1) e = " << e << endl;}
int fa() {return A::fa()+1000;}
int fE() {return fb()+fc()+A::fa()+e;}
private:
int e;
};
int main()
{
A *a = NULL;
a = new A;
cout << "A::fa = " << a->fa() << endl;
delete a;
cout << "=============\n";
a = new E(10,5);
cout << "A::fa() = " << a->A::fa() << endl;
cout << "E::fa() = " << a->fa() << endl;
cout << "=============\n";
delete a;
E e;
cout << "fE() = " << e.fE() << endl;
return EXIT_SUCCESS;
}
6.1 Ассоциация 1:1
// lab3.cpp: определяет точку входа для консольного приложения.
#include "stdafx.h"
#include "conio.h"
#include <iostream>
#include <locale>
using namespace std;
class F;
class E {
F *f;//private
int e;
public:
E() {e = 6; cout << "E e = " << e << endl;}
void link(F &f) {this->f = &f; }
void M() { cout << "class E e\n"; }
F* getF() { return f; }
};
class F {
E* e;//private
int f;
public:
F() {f = 66; cout << "F f = " << f << endl;}
void link(E &e) {this->e = &e; }
void M() { cout << "class F f\n"; }
E* getE() { return e; }
};
int main()
{
setlocale (LC_ALL,"Russian");
E e;
F f;
e.link(f);
f.link(e);
e.getF()->M();
f.getE()->M();
cout << "class E e\a" << endl;
cout << "class F f\a" << endl;
_getche();
return 0;
}
6.2 Ассоциация 1:N
// lab3_1-n.cpp Ассоциация 1-N
#include "stdafx.h"
#include <iostream>
using namespace std;
const int N = 5;
class E;
class D {
public:
D() {epp = &ep[0]; i = -1; j = -1;}
int i, j;
void link(E &e) {
*epp = &e;
i++;
cout << "link D -> E[" << i << "]; pointer = " << *epp << endl;
if (epp == &ep[N-1]) {
epp = &ep[0];
} else {
epp++;
}
}
void M(){cout << "class D\n";}
E* getNext() {
if (j < i) {
j++;
return ep[j];
}
j = 0;
return ep[j];
}
protected:
E **epp;
private:
E *ep[N];
};
class E {
public:
E() {}
void link(D &d) {
cout << "link E -> D\n";
this->d = &d;
}
void M() {cout << "class E\n";}
D* getD() {return d;}
protected:
D* d;
};
int _tmain(int argc, _TCHAR* argv[])
{
D d; E e[N]; int i;
for (i = 0; i < N; i++) {
e[i].link(d);
d.link(e[i]);
}
d.getNext()->M();
d.getNext()->M();
d.getNext()->M();
return 0;
}
7.1 Использование: клиент-сервер
| |||||
// lab4.cpp: Использование: клиент-сервер
#include "stdafx.h"
#include <iostream>
using namespace std;
class D { //сервер
int d;
public:
D():d(5) {}
int getD() {return d;}
};
class E { //клиент
int e;
public:
E():e(2) {}
void me(D &d) {e += d.getD();} //передача для метода me объекта класса D
int getE() {return e;}
};
int _tmain(int argc, _TCHAR* argv[])
{
D d; E e;
cout << "d = " << d.getD() << endl;
cout << "e = " << e.getE() << endl;
e.me(d); // категория клиент-сервер между объектами
cout << "======================\n";
cout << "d = " << d.getD() << endl;
cout << "e = " << e.getE() << endl;
return 0;
7.2 Использование: общность
| |||||
|
// lab4_obsh.cpp: Использование: общность
#include "stdafx.h"
#include <iostream>
using namespace std;
class D {
int d;
friend class E;//дружественный класс для Е, можно просмотреть элементы класса D
public:
D():d(100) {}
int getd() {return d;}
};
class E {
int e;
public:
E(D *dp):e(dp->d) {}
int getE() {return e;}
};
int _tmain(int argc, _TCHAR* argv[])
{
D *dp = NULL;
dp = new D;
E e(dp);
cout << e.getE() << endl;
return 0;
}
8.1 Конкретизация функции
// lab5_funk.cpp: конкретизация функции
#include "stdafx.h"
#include <iostream>
#include <locale>
using namespace std;
template <class T>
void swap1 (T& x, T& y) { \\конкретизация ф-и
T temp;
temp = x;
x = y;
y = temp;
}
class A {
int a;
double z;
public:
A() { a = 0; }
A(int a, double d): a(a),z(z) {}
int getA() { return a; }
double getZ() { return z; }
};
int _tmain(int argc, _TCHAR* argv[])
{
setlocale (LC_ALL,"Russian");
A a(5, 1.5);// создаётся экземпляр класса со значениями переменных
A b(7, 3.33);// тоже самое, только другой объект
swap1(a, b);//ф-я обменивается переменными(этот случай)
cout << a.getA() << endl;
cout << a.getZ() << endl;
cout << b.getA() << endl;
cout << b.getZ() << endl;
return 0;
}
8.2 Конкретизация класса
// lab5_class.cpp: Конкретизация класса
#include "stdafx.h"
using namespace std;
template <class T>
class D{
T z;//произвольный тип Т переменной z
public:
D() {}
void swap(T &x) {
T temp;// переменная temp является объектом класса Е(этот случай)
temp = z;
z = x;
x = temp;
}
T* getZ() { return &z; }
};
class E {
int e;
public:
E(): e(0) {}
E(int e): e(e) {}
int getI() { return e; }
};
int _tmain(int argc, _TCHAR* argv[])
{
setlocale (LC_ALL,"Russian");
D <E> a; // тип Т, тип класса Е
E e(7);
a.swap(e);
cout << a.getZ()->getI() << endl;
cout << e.getI() << endl;
return 0;
}