Головна » Статті » С++ » Класи та структури

Перевантаження операторів в С++
Перевантаженн опрераторів " + ", " - ", " * ", " / " для дробів
#include<iostream>
#include<cmath>
using namespace std;
class division
{
private:
    int a;
    int b;
public:
    division(int x, int y)
    {
        a = x;
        b = y;
    }
    division operator+(division obj)
    {
        a = a * obj.b + b * obj.a;
        b = b * obj.b;
        return (*this);
    }
    division operator-(division obj)
    {
        a = a * obj.b - b * obj.a;
        b = b * obj.b;
        return (*this);
    }
    division operator*(division obj)
    {
        a = a * obj.a;
        b = b * obj.b;
        return (*this);
    }
    division operator/(division obj)
    {
        a = a * obj.b;
        a = a * obj.a;
        return (*this);
    }
    division operator=(division obj)
    {
        a = obj.a;
        b = obj.b;
        return (*this);
    }
    double show()
    {
        return((double)(a) / (double)(b));
    }
};

int main()
{
    int a;
    int b;
    char str;
    cout << "a= ";
    cin >> a;
    cout << "b= ";
    cin >> b;
    division obj1(a, b);
    cout << "a= ";
    cin >> a;
    cout << "b= ";
    cin >> b;
    division obj2(a, b);
    cout << "1. +" << endl;
    cout << "2. -" << endl;
    cout << "3. *" << endl;
    cout << "4. /" << endl;
    cin >> str;
    if (str == '1')
    {
        obj1 = obj1 + obj2;
        cout << obj1.show() << endl;
    }
    else if (str == '2')
    {
         obj1 = obj1 - obj2;
         cout << obj1.show() << endl;
    }
    else if (str == '3')
    {
        obj1 = obj1 * obj2;
        cout << obj1.show() << endl;
    }
    else if (str == '4')
    {
        obj1 = obj1 / obj2;
        cout << obj1.show() << endl;
    }
    else
        cout << "WARNING";
    system("pause");
}
Категорія: Класи та структури | Додав: Undertaker (13-05-2018) | Автор: Undertaker
Переглядів: 203 | Теги: клас, класи, класи в С++, Operator, оператори, перевантаження операторів, c++ | Рейтинг: 5.0/1
Всього коментарів: 0
avatar