DEV Community

Mujahida Joynab
Mujahida Joynab

Posted on

Binary and Unary operator

#include <iostream>
using namespace std;

class Number{
    int value ;
    public:

    Number(int v = 0 ) : value(v) {} 
    Number operator+(const Number &obj) const{
        return Number(value + obj.value) ;
    }
    void display() const{
        cout << "Value : " << value << endl ;
    }
};

int main(){
    Number num1(10) ;
    Number num2(20) ;
    Number sum = num1 + num2 ;

    num1.display() ;
    cout << endl ;
    num2.display() ;
    cout << endl ;
    sum.display() ;
}
Enter fullscreen mode Exit fullscreen mode

Unary Operator

#include <iostream>
using namespace std;

class Number
{
    int value;

public:
    Number(int v = 0) : value(v) {}

    Number operator-() const
    {
        return Number(-value);
    }

    int display() const
    {
        cout << "Value: " << value << endl;
        return value;
    }
};

int main()
{
    Number num1(10);
    Number num2 = -num1;


    cout << "Returned Values: " << num1.display() << " " << num2.display() << endl;

    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)