Частина тексту файла (без зображень, графіків і формул):
МІНІСТЕРСТВО ОСВІТИ І НАУКИ УКРАЇНИ
Національний університет “Львівська політехніка”
Кафедра інформаційних систем та мереж
Лабораторна робота №4
Перевантаження операцій.
Мета полягає у вивченні способів перевантаження операцій С++ та їх
використання для роботи з об’єктами.
16.Створити клас дійсних чисел ( у закритій частині класу знаходиться значення дійсного типу). Визначити необхідні конструктори, деструктор.
Перевантажити операції: + додавання, - віднімання, * множення, / ділення, () дробова частина числа, [] ціла частина числа. Визначити потокові операції введення-виведення.
Текст програми:
#include <iostream>
#include <math.h>
using namespace std;
class DDigit{
private:
double value;
public:
DDigit() { value = 0; }
~DDigit() { value = 0; }
DDigit(double _value) { value = _value; }
DDigit operator+(const DDigit&);
DDigit operator-(const DDigit&);
DDigit operator*(const DDigit&);
DDigit operator/(const DDigit&);
long operator()(void);
double operator[](int);
friend istream& operator>>(istream&, DDigit&);
friend ostream& operator<<(ostream&, DDigit&);
};
DDigit DDigit::operator+(const DDigit& b) { return DDigit(value + b.value); }
DDigit DDigit::operator-(const DDigit& b) { return DDigit(value - b.value); }
DDigit DDigit::operator*(const DDigit& b) { return DDigit(value * b.value); }
DDigit DDigit::operator/(const DDigit& b) { return DDigit(value / b.value); }
long DDigit::operator()(void){ return floorl(value); }
double DDigit::operator[](int n){
double p = pow(10,n);
return floor((value - floor(value))*p)/p;
}
istream& operator>>(istream& stream, DDigit& p){
cout<<"Enter value: "; stream>>p.value;
return stream;
}
ostream& operator<<(ostream& stream, DDigit& p){
stream<<"Value: "<<p.value;
return stream;
}
void main(){
DDigit d1,d2(2.5);
cout<<"Enter D1\n";
cin>>d1;
cout<<"D1: "<<d1<<"\tD2: "<<d2<<endl;
cout<<"D1 + D2 = "<<d1 + d2<<endl;
cout<<"D1 - D2 = "<<d1 - d2<<endl;
cout<<"D1 * D2 = "<<d1 * d2<<endl;
cout<<"D1 / D2 = "<<d1 / d2<<endl;
cout<<"D2() = "<<d2()<<endl;
cout<<"D2[3] = "<<d1[3]<<endl;
system("pause");
}
Результат виконання:
/
Висновок: на даній лабораторній роботі я вивчив способи перевантаження операцій С++ та їх використання для роботи з об’єктами.