/*i want to overloaded operator in my program. but i dnt know how to add overloaded + operator in this prgram. plzzzzzzzzz help me to solve this problem*/
#include<iostream.h>
class rational{
private :
int numerator, dnomenator ;
void reduction();
public :
rational () //default contructer
{
numerator=dnomenator=1;
}
rational (int num, int dnum) //parameterised constructer
{
numerator=num;dnomenator=dnum;
reduction();
}
void show();
rational operator +();
};
rational rational ::operator +(){
rational sum;
sum=numerator+dnomenator;
return sum;
}
void rational ::show(){
cout<<numerator<<"/"<<dnomenator<<endl;
}
void rational::reduction()//reduces the fraction
{
int largest;
largest = numerator > dnomenator ? numerator : dnomenator;
/*if(numerator>dnomenator)
{
largest=dnomenator;
}
else
{
largest=numerator;
}*/
int gcd = 0; // greatest common divisor
for ( int count= 2; count <= largest; count++ )
if ( numerator % count == 0 && dnomenator % count == 0 )
gcd = count;
if (gcd != 0)
{
numerator /= gcd;
dnomenator /= gcd;
}
}
int main()
{
rational r;
rational c(4,6);
c.show();
return 0;
}

HASHMI007
Recommended Answers
Jump to PostTo add overloading operators to a class definition, you need to add them as a FRIEND function.
friend <type_name> operator <operator>(const <type_name>& var1, const <type_name>& var2) // Example - rational is a class name not shown but defined else where friend rational operator+(const rational& var1, const rational& …
Jump to PostPlease reread what I wrote, then check your answer with mine. Do they look similar? Do they have the same amount of parameters? You also declined to add the friend function declaration in the class definition, without it, the class will not know where to look for the + operator.
…
Jump to Postrational rational ::operator +(rational r){ rational sum; sum.numerator =numerator+sum.numerator; sum.dnomenator=dnomenator+sum.dnomenator; cout<<"The sum afer adeng both fraction is :"<<endl; return sum; }
Few things wrong with the logic of this.
…
1. You need to add two separate objects together, not one object and the sum of two objects.
All 10 Replies
Saith 74 Junior Poster
veda&& -2 Newbie Poster
Süspeñce commented: what is this..????/ +0

HASHMI007
Saith 74 Junior Poster

HASHMI007
USMAN ZAFAR -7 Newbie Poster
USMAN ZAFAR -7 Newbie Poster
Saith 74 Junior Poster
Saith 74 Junior Poster

HASHMI007
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.