
Int main(int argc, char* argv[])
{
setlocale(LC_ALL,"rus");
cout << "\n rabotaet Lab5_6.cpp " << endl;
CBook book ;
char stroka_vvoda[10];
cout <<endl<< "Введите автора " << endl;
cin >> stroka_vvoda;
book.setAuthor ( stroka_vvoda ) ;
// book.setAuthor ( "Robert Lafore" ) ;
cout << "\n отработал setAuthor pole = " << book.getAuthor() << endl;
book.setTitle ( "Object-Oriented Programming in C++" ) ;
cout << "\n отработал setTitle pole = " << book.getTitle() << endl;
book.setYear ( 2004 ) ;
view ( "book", book ) ;
cout << "\n отработал view " << endl;
CBook *pnt ;
pnt = new CBook ;
pnt->setAuthor ( "pntAutor" ) ;
pnt->setTitle ( "pntTitle" ) ;
pnt->setYear ( 2010 ) ;
view ( "pointer pnt", *pnt ) ;
system("pause");
return 0;
}
void view ( char *s, CBook &o )
{
cout << "\nState of object \' " << s << " \'\n" ;
cout << "Author:\t" << o.getAuthor ( ) << endl ;
cout << "Title:\t" << o.getTitle ( ) << endl ;
cout << "Year:\t" << o.getYear ( ) << endl << endl ;
}
Частина 2
Спроектував клас, його конструктор за замовчуванням і деструктор, методи встановлення та отримання значень полів, використав розроблені методи для роботи з об’єктами класу.
Клас, містить наступні поля: прізвище, станні показники єлектрорахівника, сума до сплати.
Файл специфікації класу:
Файл реалізації класу:
Головна функція програми:
//Arrive.h
#pragma once
class Arrive
{
private:
char n_place [50] ;
int n_price, n_number ;
public:
void setPlace(const char*);
void setPrice(int);
void setNumber(int);
char* getPlace(void);
int getPrice(void);
int getNumber(void);
Arrive(void);
~Arrive(void);
};
//Arrive.cpp
#include "StdAfx.h"
#include "Arrive.h"
#include "iostream"
#include "string"
using namespace std;
void Arrive::setPlace (const char* str)
{ cout<<endl<<"Work setPlace "<<str<< endl;
n_place[0]='\0' ;
strcat(n_place, str);
cout<<n_place<<endl;
cout<<"End work of setPlace"<<endl<<endl;
};
void Arrive::setNumber (int num)
{
n_number=num;
};
void Arrive::setPrice (int pr)
{
n_price=pr;
};
char* Arrive::getPlace (void)
{
return n_place;
};
int Arrive::getPrice (void)
{
return n_price;
};
int Arrive::getNumber (void)
{
return n_number;
};
Arrive::Arrive () : n_price(0), n_number(0)
{
n_place[0]='\0';
cout<<"Constr "<<this;
};
Arrive::~Arrive()
{
cout<<"Dectr "<<this<<endl;
};
//Lab5_3.cpp
#include "stdafx.h"
#include "iostream"
#include "Arrive.h"
using namespace std ;
void view (Arrive&o)
{
cout<<"Author: "<<o.getPlace( )<<endl;
cout<<"Title: "<<o.getPrice( )<<endl;
cout<<"Year: "<<o.getNumber( )<<endl<<endl;
}
Int main(int argc, char* argv[])
{
Arrive arr;
char str[10];
int pr, num;
cout<<endl<<"Input place: ";
cin>>str;
arr.setPlace(str);
cout<<"End work of setPlace, pole= "<<arr.getPlace()<<endl;
cout<<"Input price: ";
cin>>pr;
arr.setPrice(pr);
cout<<"pole= "<<arr.getPrice()<<endl;
cout<<endl<<"Input number: ";
cin>>num;
arr.setNumber(num);
view(arr);
cout<<"PONTER"<<endl;
Arrive *pnt ;
pnt=new Arrive;
pnt->setPlace("Place");
pnt->setNumber(102);
pnt->setPrice(1500);
view(*pnt);
system("PAUSE");
return 0;
};
Висновок: спроектував, відлагодив та протестував розроблені функції-члени класу, використав розроблені методи для роботи з об’єктами класу.
Лабораторна робота №7-8
Проектування та створенння програми з перевантаженнням імен функцій.
Мета: навчитись проектувати та створювати програми з перевантаженням імен функцій.
Хід роботи
Запустив Microsoft Visual C++ та створив проект типу Windows Console Application.
Спроектував та створив программу, яка здійснює реверс елементів массиву.
Код програми:
//#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
//перестановки для чисел
void swapR(int&rx,int&ry)
{
int t=rx; rx=ry;ry=t;
}
//перестановки для строки
void swapR(char&rx,char&ry)
{
char t=rx; rx=ry;ry=t;
}
//реверс массива чисел
void reverseArray(int*p,int=10)
{
for (int i=0,j=10-1;i<j;i++,j--)
swapR(p[i],p[j]);
}
//реверс части символного массива
int*reverseArray(const int*pIn,int top, int end)
{
if(end<=top) return 0;
int size=end-top+1;
int*pRes=new int [size];
int i,j,ir,jr;
for(i=top,j=end,ir=0,jr=size-1;i<j;)
{
pRes[ir++]=pIn[j--];
pRes[jr--]=pIn[i++];
}
if(i==j) pRes[ir]=pIn[i];
return pRes;
}
//реверс строки
char*reverseArray(const char*p)
{
char*pOut=new char[strlen(p)+1];
strncpy(pOut,p,strlen(p)+1);
char*pTop=pOut;
char*pEnd=pOut+strlen(pOut)-1;
while (pTop<pEnd)
swapR(*pTop++,*pEnd--);
return pOut;
}
//вывод на екран
void view(const int*arr,int count)
{
for(int i=0;i<count;i++)
cout<<endl<<"\t i="<<i<<" "<<arr[i]<<endl;
}
int main()
{
int ar[10]={1,2,3,4,5,6,7,8,9,10};
cout<<" Initial array "<<endl;
view(ar,10);
//реверс всего массива
reverseArray(ar);
cout<<endl<<" Reverse array "<<endl;
view(ar,10);
//реверс части массива
int*p=reverseArray(ar,5,9);
cout<<endl<<" Reverse part array "<<endl;
view(p,5);
//реверс строки
char*s="NOMEL ON NOLEM ON ";
char*pr=reverseArray(s);
cout<<endl<<" Initial string - "<<s<<endl;
cout<<" Reverse string - "<<pr<<endl<<endl<<endl<<endl;
system("pause");
return 0;
}
Копія вікна виконання програми:
Частина 2
Спроектував та створив програму, що містить перевантажені функції.
Завдання: створити перевантажені функції розрахунку об’ємів кубу, конуса, призми з правильним трикутником в основі.
Код програми:
// 8.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
//объем куба
double Ob(double a)
{
double V=0;
V=pow(a,3);
return V;
}
//объем призмы
double Ob(double l, double a)
{
double S=1;
double V=0,n=3;
S=((pow(a,2)*(sqrt(n)))/4);
V=S*l;
return V;
}
//объем конуса
double Ob(double r, double h, double pi)
{
double V=0;
V=0.333*pi*(pow(r,2))*h;
return V;
}
int _tmain(int argc, _TCHAR* argv[])
{
double a,h,r;
setlocale(LC_ALL,"rus");
cout<<" \t Вычисление объема куба"<<endl<<endl;
do{
cout<<" Введите длину ребра: ";
cin>>a;}while(a<=0);
cout<<endl<<" Объем куба: "<<Ob(a)<<endl;
cout<<endl<<endl<<" \t Вычисление объема конуса"<<endl<<endl;
do{
cout<<" Введите радиус основы ";
cin>>r;}while(r<=0);
do{
cout<<" Введите высоту конуса: ";
cin>>h;}while(h<=0);
cout<<endl<<" Объем конуса: "<<Ob(r,h,3.1415)<<endl;
cout<<endl<<endl<<" \t Вычисление объема призмы с правильным треугольником в основе"<<endl<<endl;
do{
cout<<" Введите длину основы: ";
cin>>a;}while(a<=0);
do{
cout<<" Введите длину бокового ребра призмы: ";
cin>>h;}while(h<=0);
cout<<endl<<" Объем призмы: "<<Ob(h,a)<<endl;
cout<<endl<<endl<<endl;
system("pause");
return 0;
}
Копія вікна виконання програми:
Висновок: Під час виконання лабораторної роботи я навчився проектувати та створювати програми з перевантаженням імен функцій, виконувати реверс елементів масиву, та программно обчислювати об'єми декількох геометричних фігур.
Лабораторна робота № 9-10
Проектування та створення програми з використанням функцій-членів та дружніх функцій
Мета: навчитись проектувати та створювати програми з використанням функцій-членів та дружніх функцій.
Хід роботи
Запустив Microsoft Visual C++ та створив проект типу Console application.
Створив новий клас, що має конструктор, деструктор, та методи для роботи з полями об’єктів.
До файлу специфікації додав наступний код
class DF
{
int*mas;
int raz_mas;
public:
DF(int);
virtual ~DF();
void SeMas();
void PrintMas();
friend int SumMas(DF*,int,int);
friend int ProizMas(DF&,int,int);
};
До файлу реалізації класу додав такий код
// DF.cpp: implementation of the DF class.
#include "DF.h"
#include <iostream.h>
using namespace std;
DF::DF(int razmer):raz_mas(razmer)
{
cout<<" raz_mas = "<<raz_mas<<endl;
mas=new int [raz_mas];
}
DF::~DF()
{
delete [] mas;
}
void DF::SeMas()
{
cout<<" raz_mas "<<raz_mas<<endl;
for(int i=1;i<=raz_mas;i++)
{
cout<<" Vvod "<<i<<endl;
cin>>mas[i];
}
cout<<" Massive vveden !"<<endl;
}
void DF::PrintMas()
{
cout<<"\t Elementi massiva "<<endl;
for(int i=1;i<=raz_mas;i++)
{
cout<<" "<<mas[i];
}
cout<<" "<<endl;
}
До головної функції програми додав наступний код
#include <iostream.h>
#include <stdlib.h>
#include "DF.h"
using namespace std;
int SumMas(DF*Obj1,int n1,int n2)
{
int sum_mas(0);
for(int i=n1;i<=n2;i++)
sum_mas+=Obj1->mas[i];
cout<<" \tOtraboal Sum_mas "<<endl<<" sum_mas = "<<sum_mas<<endl;
return sum_mas;
}
int ProizMas(DF& Obj2, int n1, int n2)
{
int proiz_mas(1);
for(int i=n1;i<=n2;i++)
proiz_mas*=Obj2.mas[i];
cout<<" \tOtrabotal Proiz_mas "<<endl<<" proiz_mas = "<<proiz_mas<<endl;
return proiz_mas;
}
int main()
{
int r,S1,P1,sg1,sg2,pg1,pg2;
do{
cout<<" Vvedite razmer massiva "<<endl;
cin>>r;
}while(r<1);
DF Ob1(r);
Ob1.SeMas();
Ob1.PrintMas();
cout<<" vvedite granizi vicheslenia summi ot 1 do "<<r<<endl<<endl;
do{
cout<<" Nignjaja ";
cin>>sg1;
}while (sg1<1);
do{
cout<<" Verhnaja ";
cin>>sg2;
}while(sg2>r);
S1=SumMas(&Ob1,sg1,sg2);
cout<<"\t S1= "<<S1<<endl;
cout<<" vvedite granizi vicheslenia proiazvedenia ot 1 do "<<r<<endl<<endl;
do{
cout<<" Nignjaja ";
cin>>pg1;
}while (pg1<1);
do{
cout<<" Verhnaja ";
cin>>pg2;
}while(pg2>r);
P1=ProizMas(Ob1,pg1,pg2);
cout<<"\t P1= "<<P1<<endl;
system("pause");
return 0;
}
Копія вікна виконання програми
Частина 2
Створив проект із класом та дружніми функціями для розрахунку наступного рівняння:
Створив простий консольний додаток, що містить клас myC
Файл специфікації класу myC.h містить наступний код
// myC.h: interface for the myC class.
#pragma once
class myC
{
private:
double x,t,y,z;
public:
myC();
virtual ~myC();
void set(void);
friend double Run(myC &);
friend void print(myC &);};
Файл реалізації класу myC.cpp:
include "myC.h"
#include <iostream>
using namespace std;
myC::myC()
{
x=0;y=0;z=0;
}
myC::~myC()
{}
void myC::set()
{
cout<<" VVedite x "<<endl;
cin>>x;
cout<<" VVedite y "<<endl;
cin>>y;
cout<<" VVedite z "<<endl;
cin>>z;}
Головна функція програми, містить реалізацію дружніх функцій
#include "myC.h"
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
double Run(myC &c)
{
c.t=((pow(c.x,(c.y/c.x))));
c.t=c.t- (pow((c.y/c.x),1.0/3.0));
c.t=fabs(c.t)+((c.y-c.x)*(((cos(c.y)-(c.z/(c.y-c.x)))/(1+(pow((c.y-c.x),2.0))))));
return c.t;
}
void print(myC &c)
{
cout<<" x = "<<c.x<<endl;
cout<<" y = "<<c.y<<endl;
cout<<" t = "<<c.t<<endl;
}
int main()
{
myC C;
C.set();
cout<<" otvet = "<<Run(C)<<endl;
print(C);
system("pause");
return 0;
}
Копія вікна виконання програми
Висновок: під час виконання лабораторної роботи я навчився проектувати та створювати програми з використанням функцій-членів та дружніх функцій.
Лабораторна робота № 11-12.
Проектування та створення програми з перевантаженням операцій за допомогою функцій-членів.
Мета: навчитись проектувати та створювати програми з перевантаженням операцій за допомогою функцій-членів.
Хід роботи
Запустив Microsoft Visual C++ та створив проект типу Console application.
Створив новий клас, що має конструктор, деструктор, та методи для роботи з полями об’єктів.
Файл специфікації D.h містить оголошення типу класу D. У класі оголошені закриті дані.
#pragma once
class D
{
int *m_p;
int m_n;
public:
D(int =10);
D(D&);
virtual ~D();
int getN(void) const;// возврат размера массива
int& operator [] (const unsigned int) const;
D& operator =(D&);
D operator +(const D&) const; // сложени объектов
D operator + (const int&) const; // сложние объекта с числом
D operator - (const D&) const; // вычитание объектов
friend void view(const D&);
};
Файл реалізації D.cpp :
#include "D.h"
D::D(int n): m_n(n)
{
m_p=new int[m_n];
for(int i=0; i <m_n; i++)
m_p[i]=0;
}
D::~D()
{delete [ ] m_p;}
D::D(D& o) : m_n (o.m_n)
{
m_p=new int [m_n];
for(int i =0; i<m_n; i++)
m_p[i]=o.m_p[i];}
int D::getN(void) const
{return m_n;}
int& D::operator [](const unsigned int i)const
{return m_p[i];}
D& D::operator =(D& right)
{
if(m_n!=right.m_n)
{
delete [] m_p;
m_n=right.m_n;
m_p=new int [m_n];
}
for(int i=0;i<m_n;i++)
m_p[i]=right.m_p[i];
return *this;
}
D D::operator +(const D& right) const
{
D tmp(m_n);
for(int i=0;i<tmp.m_n;i++)
tmp.m_p[i]=m_p[i]+right.m_p[i];
return tmp;
}
D D::operator+(const int& right) const
{
D tmp(m_n);
for(int i=0;i<tmp.m_n;i++)
tmp.m_p[i]=m_p[i]+right;
return tmp;
}
D D::operator - (const D& right) const
{
D tmp(m_n);
for(int i=0;i<tmp.m_n;i++)
tmp.m_p[i]=m_p[i]-right.m_p[i];
return tmp;
}
Головна функція програми:
#include <iostream>
#include "D.h"
using namespace std;
void view(const D& o)
{
for(int i=0; i<o.m_n; i++)
cout<<o[i]<<'\t';
cout<<endl;
}
int main()
{
D o1(5),o2(5);
for(int i=0; i<o1.getN(); i++)
{
o1[i]=(i+1)*2;
o2[i]=i;
}
cout<<endl<<"o1\t\t ";
view(o1);
cout<<endl<<"o2:\t\t ";
view(o2);
D res;
res=o1+o2;
cout<<endl<<"res=o1+o2:\t";
view(res);
int x(5); D o3(5);
cout<<endl<<"o3:\t\t";
view(o3);
res=o3+x;
cout<<endl<<"o3+x:\t\t";
view(res);
res=o3-o2;
cout<<endl<<"res=o3-o2:\t";
view(res);
res=o2-o3;
cout<<endl<<"res=o2-o3:\t";
view(res);
cout<<"\no1:\t\t"; view(o1);
cout<<"\no2:\t\t"; view(o2);
cout<<"\no3:\t\t"; view(o3);
system("pause");
return 0;
}
Копія вікна виконання програми
Висновок: Під час виконання лабораторної роботи я навчився проектувати та створювати програми з перевантаженням операцій за допомогою функцій-членів.
Лабораторна робота № 13-14
Проектування та створення програми з перевантаженням операторів за допомогою дружніх функцій
Мета: навчитись проектувати та створювати програми з програми з перевантаженням операторів за допомогою дружніх функцій.
Хід роботи
Запустив Microsoft Visual C++ та створив проект типу Console application.
Створив новий клас, що має конструктор, деструктор, та методи для роботи з полями об’єктів.
До файлу специфікації додав наступний код
#pragma once
class cpoint
{
public:
int mx,my;
cpoint();
cpoint(int,int);
~cpoint();
friend cpoint& operator ++(cpoint&);
friend cpoint& operator ++(cpoint&,int);
};
До файлу реалізації класу додав такий код
#include "StdAfx.h"
#include "cpoint.h"
cpoint::~cpoint(void)
{
}
cpoint::cpoint(): mx(0),my(0){}
cpoint::cpoint(int x,int y):mx(x),my(y){}
До головної функції програми додав наступний код
#include "stdafx.h"
#include "cpoint.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
cpoint& operator++(cpoint& o)
{
++o.mx;
++o.my;
return o;
}
cpoint& operator++(cpoint& o,int unused)
{
o.mx++;
o.my++;
return o;
}
int _tmain(int argc, _TCHAR* argv[])
{
cpoint a,b(-8,6);
++a; cout<<a.mx<<"\t"<<a.my<<endl;
b++; cout<<b.mx<<"\t"<<b.my<<endl;
system("pause");
return 0;
}
Копія вікна виконання програми
Частина 2
Запустив Microsoft Visual C++ та створив проект типу Console application.
Створив новий клас, що має конструктор, деструктор, та методи для роботи з полями об’єктів.
До файлу специфікації додав наступний код
class d
{int* m_p ; int m_n;
public:
d(int=10);
d (d&);
~d();
int getN (void) const;
int& operator [ ] ( const unsigned int) const;
d& operator = (d&);
friend d operator + (const d&, const d&);
friend d operator + (const d&, const int&);
friend d operator + (const int&, const d&);
friend d operator - (const d&, const d&);
};
До файлу реалізації класу додав такий код
#include "StdAfx.h"
#include "d.h"
d::d(int n):m_n(n)
{
m_p = new int [ m_n ];
for (int і = 0; і < m_n; і++)
m_p [ і ] = 0 ;
}
d::d(d&o):m_n(o.m_n)
{
m_p = new int [ m_n ];
for (int і = 0; і < m_n; і++)
m_p [ і ] = o.m_p [ і ];}
d::~d() {delete []m_p;}
int d :: getN (void) const { return m_n ;}
int& d :: operator [ ] (const unsigned int і) const
{ return m_p [ і ]; }
d& d :: operator = (d& right)
{
if (m_n != right.m_n)
{
delete [ ] m_p ;
m_n = right.m_n;
m_p = new int [ m_n ];
}
for (int і = 0; і < m_n; і++)
m_p [ і ] = right.m_p [ і ];
return *this;
}
До головної функції програми додав наступний код
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
#include "d.h"
// прототипы глобальных функций
d operator + (const d&, const d&); // сложение объектов
d operator + (const d&, const int& ); // сложение объекта с числом
d operator + (const int&, const d&); // сложение числа с объектом
d operator - (const d&, const d&); // вычитание объектов
void view (const d&); // вывод состояния объекта
// main.cpp - главная функция