Write a Program to overload the unary minus operator using friend function.

Sep 15, 2018

Program:

// program to overload the unary minus 
// operator using FRIEND functions

#include<iostream>
using namespace std;

class Number{
	private:
		float number;
	public:
		// member initialize list
		Number(float n = 0):number(n){}
		// friend function declaration for the unary minus
		friend Number operator -(Number &n);
		// function to display the number
		void display(){
			cout<<"Number:"<<number<<endl;
		}
};

// freind function defination
Number operator -(Number &n){
	n.number = -n.number;
	return Number(n.number);
}

int main(){
	Number num1(10),num2;
	cout<<"Beore operation: num1 and num2 are:"<<endl;
	num1.display();
	num2.display();
	num2 = -num1;
	cout<<"After operation: num1 and num2 are:"<<endl;
	num1.display();
	num2.display();
	return 0;
}

 

Sample Run:

Beore operation: num1 and num2 are:
Number:10
Number:0
After operation: num1 and num2 are:
Number:-10
Number:-10

Related


Tools/Apps





© Nepal Exchange Rates