Header Ad

C++ program to overload binary operators

In this post, we will write a C++ program to overload binary operators.

C++ program to overload binary operators


C++ program to overload binary operators.

#include<iostream>
#include<conio.h>

class weight
{
    private:
        int kg,g,mg;

    public:
        weight()
        {
            kg = 0;
            g = 0;
            mg = 0;
        }
        weight(int a, int b, int c)
        {
            kg = a;
            g = b;
            mg = c;
        }
        getdata()
        {
            std::cout<<"Enter the kg = ";
            std::cin>>kg;
            std::cout<<"Enter the g = ";
            std::cin>>g;
            std::cout<<"Enter the mg = ";
            std::cin>>mg;
        }
        showdata()
        {
            std::cout<<"The weight is = "<<kg<<" "<<g<<" "<<mg<<std::endl;
        }
        weight operator + (weight w5)
        {
            int i = kg+w5.kg;
            int j = g+w5.g;
            int k = mg+w5.mg;

            return weight(i,j,k);
        }
        weight operator - (weight w5)
        {
            int i = kg-w5.kg;
            int j = g-w5.g;
            int k = mg-w5.mg;
            return weight(i,j,k);
        }
        weight operator * (weight w5)
        {
            double i = 5*w5.kg;
            double j = 5*w5.g;
            double k = 5*w5.mg;
            return weight(i,j,k);
        }
};

int main()
{
    system("cls");

    weight w1,w3,w4,w6;
    w1.getdata();

    weight w2(15,100,150);
    w3 = w1+w2;
    w4 = w1-w2;
    w6 = w2*w1;
    w3.showdata();
    w4.showdata();
    w6.showdata();

    getch();
    return 0;
}



Output

Enter the Kg = 100
Enter the g = 900
Enter the mg = 500
Enter the weight is = 115   1000    650
The weight is = 85  800     350
The weight is = 500     4500    2500

Post a Comment

0 Comments