Вы находитесь на странице: 1из 14

Лабораторная работа №1.

Тема: Классы, объекты. Функции-члены класса в языке С++. Инкапсуляция


15 - вариант
Задание:
Расширьте тип данных двусторонняя очередь (dequeue), добавляя
функцию-член relocate (перемещение). Если двусторонняя очередь
полна, тогда вызывается relocate, и содержимое двусторонней очереди
перемещается для уравновешивания свободной памяти около центра
max_len/ 2 массива s. boolean dequeue::relocate()
Текст программы:

#include <stdio.h>
#include <stdio.h>
#include<iostream>
#include<iomanip>
using namespace std;

const int max_len = 4;


class queue
{
public:
void reset()
{
top = bottom = max_len / 2;
top--;
};
void push_t(char);
void pop_t();
void push_b(char);
void pop_b();
void print_stack();
void top_of();
void bottom_of();
int empty();
int full();
bool relocate();
private:
char s[max_len];
int bottom, top;
};
bool queue::relocate() {
if (max_len > 2) {
for (int i = max_len / 2; i > 0; i--) {
s[i] = s[bottom];
s[i + 1] = s[top];
}
return true;
}
return false;
}
int queue::empty()
{
if (top < bottom)
return 1;

return 0;
}

int queue::full()
{
if (top == max_len && bottom == 0)
return 1;
relocate();
return 0;

void queue::bottom_of()
{
if (!empty())
cout << s[bottom] << endl;
else
cout << "the queue is empty." << endl;

void queue::top_of()
{
if (!empty())
cout << s[top] << endl;
else
cout << "the queue is empty." << endl;

void queue::pop_b()
{
if (!empty())
bottom++;
}

void queue::pop_t()
{
if (!empty())
top--;
}

void queue::push_b(char a)
{
if (!full() && bottom != 0)
{
bottom--;
s[bottom] = a;

}
else
cout << "sorry,the bottom's direction is full." << endl;
}

void queue::push_t(char a)
{
if (!full() && top != max_len - 1)
{
top++;
s[top] = a;
}
else
cout << "sorry,the top's direction is full." << endl;
}

void queue::print_stack()
{
int i;
if (!empty())
{
for (i = bottom; i <= top; i++)
cout << s[i] << setw(2);

cout << endl;


}
else
cout << "the queue is empty,nothing is here." << endl;
}

int main()
{
class queue test;
int type;
char a;
test.reset();
cout << "please choose a command." << endl;
cout << "******************************" << endl;
cout << "1:" << setw(3) << " bottom of" << endl;
cout << "2:" << setw(3) << " top of" << endl;
cout << "3:" << setw(3) << " pop top" << endl;
cout << "4:" << setw(3) << " push top" << endl;
cout << "5:" << setw(3) << " pop bottom" << endl;
cout << "6:" << setw(3) << " push bottom" << endl;
cout << "7:" << setw(3) << " empty or not" << endl;
cout << "8:" << setw(3) << " full or not" << endl;
cout << "9:" << setw(3) << " print queue" << endl;
cout << "10:" << setw(3) << " reset" << endl;
cout << "0:" << setw(3) << " exit" << endl;
cout << "******************************" << endl;
cin >> type;
while (type != 0)
{
switch (type) {
case 1:test.bottom_of();
break;
case 2:test.top_of();
break;
case 3:test.pop_t();
break;
case 4:cout << "input an element:(the type is char)" << endl;
cin >> a;
test.push_t(a);
break;
case 5:test.pop_b();
break;
case 6:cout << "input an element:(the type is char)" << endl;
cin >> a;
test.push_b(a);
break;
case 7:test.empty();
if (test.empty() == 1) {
cout << "empty" << endl;
}
else cout << "not empty" << endl;
break;
case 8:test.full();
if (test.full() == 1) {
cout << "full" << endl;
}
else cout << "not full" << endl;
break;
case 9:test.print_stack();
break;
case 10:test.reset();
break;
default:return 1;
}
cin >> type;
}
test.print_stack();
return 0;
}
Результаты:
Лабораторная работа №2.
Тема: КОНСТРУКТОРЫ И ДЕСТРУКТОРЫ
15 - вариант
Задание:
Определите класс strtype_a, в состав которого входит функция-
член invert, инвертирующая строку и конструктор, параметрами его
являются номер символа, до которого будет произведено
инвертирование и сама строка. По умолчанию произвести
инвертирование всей строки.
Текст программы:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
class strtype_a {
private:
char str[200];
int num;
public:
strtype_a() {
setStr((char*)"lol");
setNum(2);
}
strtype_a(char str[],int num) {
setStr(str);
setNum(num);
}
strtype_a(char str[]) {
setStr(str);
}
void setStr(char str[]) {
sprintf(this->str, "%s", str);
}
void setNum(int num) {
this->num = num-1;
}
void invert() {
if (num > -1) {
char buff[200];
int j = 0;
for (int i = num; i >= 0; i--) {
buff[j] = str[i];
j++;
}
for (int i = 0; i < num; i++) {
str[i] = buff[i];
}
}
else {
char buff[200];
int j = 0;
for (int i = strlen(str) - 1; i >= 0; i--){
buff[j] = str[i];
j++;
}
for (int i = 0; i < strlen(str); i++) {
str[i] = buff[i];
}
}
}
char* getStr() {
return str;
}
void print() {
printf("String: %s", str);
}
};

int main() {
strtype_a a((char*)"letgo");
printf("String 'letgo' with no num\n");
a.invert();
a.print();
printf("\nString 'letgo' with num 3\n");
a.setStr((char*)"letgo");
a.setNum(3);
a.invert();
a.print();
printf("\n");
system("pause");
return 0;
}
Результаты:
Лабораторная работа №3.
Тема: НАСЛЕДОВАНИЕ
15 - вариант
Задание:
Разработать программу "картотека", с использованием
наследования от одного базового класса. Имеется класс "книга",
породить классы "данные автора", "индекс книги".
Текст программы:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

class Book {
protected:
char name[15];
char author[15];
int index;
};

class Author :Book {


public:
Author() {
sprintf(author, "noname noname");
}
void setAuthor(char author[]) {
sprintf(this->author, "%s", author);
}
void setBook(char name[]) {
sprintf(this->name, "%s", name);
}
char* getAuthor() {
return author;
}
char* getBook() {
return name;
}
};

class Index :Book {


public:
Index() {
index = 0;
}
void setIndex(int index) {
this->index = index;
}
int getIndex() {
return index;
}
};

int main() {
Index a;
Author b;
char buff[20];
sprintf(buff, "Dojh Dorian");
b.setAuthor(buff);
sprintf(buff, "Home");
b.setBook(buff);
a.setIndex(100);
printf("Book - %s; Author - %s; Index -
%d\n",b.getBook(),b.getAuthor(),a.getIndex());
system("pause");
return 0;
}
Результаты:
Лабораторная работа №4.
Тема: ПОЛИМОРФИЗМ. ПЕРЕГРУЗКА ОПЕРАЦИЙ И ФУНКЦИЙ
15 - вариант
Задание:
Ввести класс для работы с объектом "множество целых чисел".
Реализовать следующие операции:
а) удаление элемента из множества(операция -);
б) проверка наличия заданного элемента в заданном
множестве(операция /).
Членом класса сделать функцию printf() для вывода конечного
множества
Текст программы:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

class Set {
private:
int mass[100];
int max;
public:
Set();
void operator+=(int a);
void operator-(int a);
int operator/(int a);
void print();
};
Set::Set() {
max = 0;
}
void Set::operator+=(int a) {
mass[max] = a;
max++;
}
void Set::operator-(int a) {
for (int i = 0; i < max; i++) {
if (mass[i] == a) {
for (int j = i; j < max; j++) {
mass[j] = mass[j + 1];
}
max--;
}
}
}
int Set::operator/(int a) {
int isfounded = 0;
for (int i = 0; i < max; i++) {
if (mass[i] == a) {
isfounded = 1;
}
}
return isfounded;
}
void Set::print() {
for (int i = 0; i < max; i++) {
printf("%d ", mass[i]);
if (i > 40) {
printf("\n");
}
}
}

int main() {
Set a;
printf("Example:\n");
a += 5;
a += 10;
a += 15;
a += 21;
printf("was Set: ");
a.print();
a - 15;
printf("\nafter 'Set - 15':");
a.print();
printf("\nfounded element 21?(set/21):%s", (a / 21) > 0 ? "yes":"no");
printf("\nfounded element 2?(set/2):%s", (a / 2) > 0 ? "yes" : "no");
printf("\n\n\n");
printf("Let's check u now :)\nif elements = 0 - program close");
int num = 0;
int buff = 0;
do {
Set b;
printf("\n\nHow much elements? - ");
scanf("%d", &num);
if (num == 0) {
break;
}
printf("Enter %d elements:\n", num);
while (num > 0) {
scanf("%d", &buff);
b += buff;
num--;
}
printf("Set now:");
b.print();
printf("\nWhat element u want to eject from set: ");
scanf("%d", &buff);
b - buff;
printf("Set now: ");
b.print();
printf("\nWhat element u want to find: ");
scanf("%d", &buff);
printf("%s", (b / buff) > 0 ? "founded" : "not founded");
printf("\n\n");
} while (1);
printf("\n\n\n");
return 0;
}
Результаты:

Вам также может понравиться