Tuesday, 21 April 2015

Write a program that will demonstrate overloading binary operator

Write a program that will demonstrate overloading binary operator. The program that uses the following properties – class names- test; one integer type private member variables- value; two constructor function test(), test(int a); one operator overloading function test operator-(test s); one member function display(). Suppose test function has got three objects like ob1(80), ob2(50), ob3. We want to subtract the value of object ob2 from the value of ob1 and ob3 will carry the subtraction result. The display() will display the output as follows-
ob1=80
ob2=50

ob3=30

#include<iostream>
using namespace std;
class test{
int value;
public:
test()
{

}
test(int a){
value=a;
}
test operator -(test);
void display();
};

test test::operator -(test s)
{
    test t;
    t.value=s.value-value;
    return t;
}
void test::display(){


cout<<"Output="<<value<<endl;
}
int main()
{
    test ob1(80), ob2(50), ob3;
    ob3=ob2-ob1;
     ob1.display();
     ob2.display();
     ob3.display();

    return 0;
}

No comments:

Post a Comment