Skip to content

Instantly share code, notes, and snippets.

@v14dislav
Created April 11, 2019 14:24
Show Gist options
  • Save v14dislav/ac2b4ea05b6db5fe8603c4a21a6a5662 to your computer and use it in GitHub Desktop.
Save v14dislav/ac2b4ea05b6db5fe8603c4a21a6a5662 to your computer and use it in GitHub Desktop.
Operator overloading > < != ==
struct Rational
{
Rational(int numerator = 0, int denominator = 1);
void add(Rational rational);
void sub(Rational rational);
void mul(Rational rational);
void div(Rational rational);
void neg();
void inv();
double to_double() const;
Rational& operator+=(Rational rational);
Rational& operator-=(Rational rational);
Rational& operator*=(Rational rational);
Rational& operator/=(Rational rational);
Rational operator-() const;
Rational operator+() const;
bool operator<(Rational const & rational){
Rational temp=*this;
temp.sub(rational);
return temp.numerator_<0;
}
bool operator>(Rational const & rational){
Rational temp=*this;
return !(temp<rational)&&(temp!=rational);
}
bool operator==(Rational rational) const{
Rational temp=*this;
temp-=rational;
return (temp.numerator_)==0;
}
bool operator!=(Rational rational) const{
Rational temp=*this;
return !(temp==rational);
}
bool operator!=(int num) const{
Rational temp(num);
return !(temp==*this);
}
bool operator<(int num){
Rational temp=*this;
Rational temp2(num);
temp.sub(temp2);
return temp.numerator_<0;
}
bool operator>(int num){
Rational temp(num);
return !(*this<temp)&&(temp!=*this);
}
bool operator>=(int num){
Rational temp(num);
return (!(*this<temp))||(temp==*this);
}
bool operator>=(Rational const & rational) {
Rational temp=*this;
return (!(temp<rational))||(rational==temp);
}
bool operator<=(int num){
Rational temp(num);
return (!(*this>temp))||(temp==*this);
}
bool operator<=(Rational const & rational) {
Rational temp=*this;
return (!(temp>rational))||(rational==temp);
}
bool operator==(int num){
Rational temp(num);
temp-=*this;
return temp.numerator_==0;
}
int getnum(){
return numerator_;
}
int getd(){
return denominator_;
}
private:
int numerator_;
unsigned denominator_;
};
bool operator==(int num,Rational rhs){
Rational temp(num);
temp-=rhs;
return (temp.getnum())==0;
}
bool operator!=(int num,Rational rhs){
Rational temp(num);
return !(temp==rhs);
}
bool operator<(int num,Rational rhs){
Rational temp(num);
temp.sub(rhs);
return temp.getnum()<0;
}
bool operator>(int num,Rational rhs){
Rational temp(num);
return !(temp<rhs)&&(temp!=rhs);
}
bool operator>=(int num,Rational const & rhs){
Rational temp(num);
return (!(temp<rhs))||(temp==rhs);
}
bool operator<=(int num,Rational const & rhs){
Rational temp(num);
return (!(temp>rhs))||(temp==rhs);
}
Rational operator+(Rational lhs, Rational rhs);
Rational operator-(Rational lhs, Rational rhs);
Rational operator*(Rational lhs, Rational rhs);
Rational operator/(Rational lhs, Rational rhs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment