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

Министерство образования республики Молдова

Технический университет Молдовы


Факультет Вычислительной техники, Информатики и
Микроэлектроники

Отчёт
по лабораторной работе №2
по ООП

Выполнил cтудент гр. SI-182 : Кравец В.

Проверил: Митителу В.

Кишинёв 2019
Конструктор – функция инициализации объектов класса

Цели работы:
 изучение основ определения и использования конструкторов;
 изучение основ определения и использования деструкторов;
 изучение типов конструкторов;

Задание :

а) Создать класс String – строка, используя динамическую память. Определить конструкторы:


по умолчанию, копий и с параметром – указателем на строку типа char. Определить функции
присваивания одной строки другой, сравнения, поиска подстроки, количества символов и др.
b) Создать класс Matrix-матрица. Данный класс содержит указатель на double, количество
строк и столбцов и переменную - код ошибки. Определить конструктор без параметров,
конструктор с одним параметром – квадратная матрица и конструктор с двумя параметрами –
прямоугольная матрица и др. Определить методы доступа: возвращение и определение
значения элемента (i,j). Определить функции сложения и вычитания (матрицы с матрицей),
умножение матрицы на матрицу. Определить умножение матрицы на число. Проверить
работу этого класса. В случае нехватки памяти, несоответствия размерностей, выхода за
пределы используемой памяти устанавливать код ошибки.

Исходный код :
//Пункт А
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
class myString{
char *p;
int n;
public:
myString()
{
p=new char[4];
strcpy(p,"YES");
n=3;
// cout<<"ctor1"<<endl;
}
myString(char *s,int n=0)
{
n=strlen(s);
p=new char[n+1];
strcpy(p,s);
// cout<<"ctor2"<<endl;
}
myString(const char *s,int n=0)
{
n=strlen(s);
p=new char[n+1];
strcpy(p,s);
// cout<<"ctor3"<<endl;
}
myString(const myString& a)
{
n=strlen(a.p);
p=new char[n+1];
strcpy(p,a.p);
// cout<<"ctor4"<<endl;
}
const myString & operator=(const myString & a)
{
if(this == &a)
return a;
delete [] p;
n=strlen(a.p);
p=new char[n+1];
strcpy(p,a.p);
// cout<<"op="<<endl;
return *this;
}
bool operator>(const myString &a)
{
return strcmp(p,a.p)>0;
}
bool operator<(const myString &a)
{
return strcmp(a.p,p)>0;
}
bool operator==(const myString &a)
{
return strcmp(p,a.p)==0;
}
bool strst(const myString &a)
{
return strstr(p,a.p)!=0;
}
int amount(const myString &a)
{
return strlen(p);
}
void printAll(const myString &a)
{
cout<<p<<endl;
}
~myString()
{
// cout<<"destr"<<p<<endl;
delete [] p;
}
};
int main()
{

myString x("bsafasdfasdf"),y("dsfgd");
x.printAll(x);
y.printAll(y);
if(x.strst(y))
cout<<"X consists Y"<<endl;
else
cout<<"X doesn't consist Y"<<endl;

if(x>y)
cout<<"x>y"<<endl;
else if(x<y)
cout<<"x<y"<<endl;
else if(x==y)
cout<<"x=y"<<endl;

cout<<"The lenght of the X is "<<x.amount(x);


x=y;
cout<<endl;
cout<<"The meaning of X after assignment"<<endl;
x.printAll(x);
return 0;
}
//Пункт Б
#include <iostream>
using namespace std;
class Matrix
{
int **arr = NULL;
int n;
int m;
int errno;
public:
Matrix()
{
// cout<<"ctor1"<<endl;
};
Matrix(int sq)
{
if(sq<=0)
return;
n = sq;
m = sq;
arr = new int*[sq];
for (int i=0; i<sq; i++)
{
arr[i] = new int[sq];
}
for (int i=0; i<sq; i++)
for (int j=0; j<sq; j++)
{
cout<<"["<<i+1<<"]"<<"["<<j+1<<"]"<<" ";
cin>>arr[i][j];
}
// cout<<"ctor2"<<endl;
}
Matrix(int rows, int cols)
{
if(rows<=0 || cols<=0)
return;
n = rows;
m = cols;
arr = new int*[n];
for (int i=0; i<n; i++)
{
arr[i] = new int[m];
}
for (int i=0; i<n; i++)
for (int j=0; j<m; j++)
{
cout<<"["<<i+1<<"]"<<"["<<j+1<<"]"<<" ";
cin>>arr[i][j];
}
// cout<<"ctor3"<<endl;
}
int getRows()
{
return n;
};
int getCols()
{
return m;
};
void printAll()
{
for (int i=0; i<n; i++)
{
for (int j=0; j<m; j++)
cout<<arr[i][j]<<" ";
putchar('\n');
}
}
int access(int i, int j)
{
// if(i<0 || j<0 || (i>n-1) || (j>m-1))
// return NULL;
return arr[i][j];
}

void multiNumber(int num)


{
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
{
arr[i][j]*=num;
}
}
};

int **sum(Matrix a,Matrix b)


{
if (a.getRows()==b.getRows() && a.getCols()==b.getCols())
{

int **result = new int *[a.getRows()];


for (int i=0; i<a.getRows(); i++)
{
result[i] = new int [b.getCols()];
}

for (int i=0; i<a.getRows(); i++)


for (int j=0; j<b.getCols(); j++)
{
result[i][j]=a.access(i,j)+b.access(i,j);
}
return result;
}
else return NULL;
}

int **diff(Matrix a, Matrix b)


{
if (a.getRows()==b.getRows() && a.getCols()==b.getCols())
{

int **result = new int *[a.getRows()];


for (int i=0; i<a.getRows(); i++)
{
result[i] = new int [b.getCols()];
}

for (int i=0; i<a.getRows(); i++)


for (int j=0; j<b.getCols(); j++)
{
result[i][j]=a.access(i,j)-b.access(i,j);
}
return result;
}
else return NULL;
}

int** multiply2matrix(Matrix a, Matrix b)


{
if(!(a.getCols() == b.getRows()))
return NULL;
int **result = new int *[a.getRows()];
for (int i=0; i<a.getRows(); i++)
{
result[i] = new int [b.getCols()];
}
for (int i=0; i<a.getRows(); i++)
for(int j=0; j<b.getCols(); j++)
{
result[i][j] = 0;
for (int k=0; k<a.getCols(); k++)
{
result[i][j]+=a.access(i,k)*b.access(k,j);
}
}
return result;
}

int main()
{
int **m, **s, **d;
cout<<"Enter elements of the first matrix"<<endl;
Matrix a(2,2);
cout<<"Enter elements of the second matrix"<<endl;
Matrix b(2,2);
cout<<"The first matrix A"<<endl;
a.printAll();
cout<<endl;
cout<<"The second matrix B"<<endl;
b.printAll();
cout<<endl;
m = multiply2matrix(a,b);
cout<<"The multiply matrix"<<endl;
for(int i=0 ; i<a.getRows(); i++)
{
for(int j=0 ; j<b.getCols(); j++)
cout<<m[i][j]<<" ";
putchar('\n');
}
cout<<endl;
cout<<"The addition matrix"<<endl;
if(sum(a,b))
{
s = sum(a,b);
for(int i=0 ; i<a.getRows(); i++)
{
for(int j=0 ; j<b.getCols(); j++)
cout<<s[i][j]<<" ";
putchar('\n');
}
}

// a.printAll();
cout<<endl;
cout<<"The difference matrix"<<endl;
if(diff(a,b))
{
d = diff(a,b);
for(int i=0 ; i<a.getRows(); i++)
{
for(int j=0 ; j<b.getCols(); j++)
cout<<d[i][j]<<" ";
putchar('\n');
}
}
// b.printAll();
cout<<endl;
cout<<"The first matrix after multiplication by a number"<<endl;
a.multiNumber(3);
a.printAll();

return 0;
}
Полученные результаты :

Пункт А

Пункт Б

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