#include <iostream>
using namespace std;
class Distance // класс английских мер длины
{
private:
int feet;
float inches;
public:
// конструктор без параметров
Distance (): feet (0), inches (0.0) { } // конструктор с двумя параметрами
Distance (int ft, float in): feet (ft), inches (in) { } // получение информации or пользователя
void getdist ()
{
cout << "nВведите футы: "; cin >> feet;
cout << "Введите дюймы: "; cin >> inches;
}
void showdist () // показ информации
{
cout << feet << "'-" << inches << "'""; }
// сложение двух длин
Distance operator+ (Distance);
};
///////////////////////////////////////////////////////////
// сложение двух длин чисел
Distance Distance::operator+ (Distance d2)
{
int f = feet + d2.feet; // складываем футы
float i = inches + d2.inches; // складываем дюймы
if (i >= 12.0) // если дюймов стало больше 12
{
i -= 12.0; // то уменьшаем дюймы на 12
f++; // и увеличиваем футы на 1
}
return Distance (f, i); // создаем и возвращаем временную переменную
}
///////////////////////////////////////////////////////////
int main ()
{
Distance dist1, dist3, dist4; // определяем переменные
dist1.getdist (); // получаем информацию
Distance dist2 (11, 6.25); // определяем переменную со значением
dist3 = dist1 + dist2; // складываем две переменные
|
|
cout << "dist1 = "; dist1.showdist (); cout << endl;
cout << "dist2 = "; dist2.showdist (); cout << endl;
cout << "dist3= "; dist3.showdist (); cout << endl;
return 0; }
Операций операции присваивания
#include <iostream>
using namespace std;
///////////////////////////////////////////////////////////
class Distance // класс английских мер длины
{
private:
int feet;
float inches;
public:
// конструктор без параметров
Distance (): feet (0), inches (0.0){ }// конструктор с двумя параметрами
Distance (int ft, float in): feet (ft), inches (in){ }
// получение информации от пользователя
void getdist ()
{
cout << "nВведите футы: "; cin >> feet;
cout << "Введите дюймы: "; cin >> inches;
}
// показ информации
void showdist ()
{
cout << feet << "’-" << inches << "'"";
}
// сравнение двух длин
bool operator< (Distance);
};
///////////////////////////////////////////////////////////
// сравнение двух длин
bool Distance::operator< (Distance d2)
{
float bfl = feet + inches /12;
float bf2 = d2.feet + d2.inches / 12;
return (bfl < bf2)? true: false;
}
///////////////////////////////////////////////7///////////
int main ()
{
Distance dist1; // определяем переменную
dist1.getdist (); // получаем длину от пользователя
Distance dist2 (6, 2.5); // определяем и инициализируем переменную
// показываем длины
cout << "ndist1 - "; dist1.showdist ();
cout << "ndist2 - "; dist2.showdist ();
// используем наш оператор
if (dist1 < dist2)
cout << "ndist1 меньше чем dist2";
else
cout << "ndist1 больше или равно чем dist2";
cout << endl;
return 0;
Перегрузка () []
int& operator[] (int i) {return arr[i];}
int operator() (int i) {return arr[i]*i;}