testing two objects as equal?

Nov 6, 2020 at 6:16am
is there a way to test to see if i can test if two objects of the same types equal each other, like if say i have a class:


class Fraction
{
public:
Fraction();
Fraction(int n, int d);
void setNumerator(int set);
void setDenominator(int set);
int getNumberator();
int getDenominator();
private:
int numerator;
int denominator;
};



and i want to test if two fraction objects are equal, is there a way i can set things up so i can do this:

//make to fraction objects
Fraction number1 = {1, 2};
Fraction number2 = {1, 2};
//test see if the two fractions are the same
bool isSame = number1 == numbers;
std::cout << isSame;


or am i stuck doing it like this

//make to fraction objects
Fraction number1 = {1, 2};
Fraction number2 = {1, 2};
//test see if the two fractions are the same
bool isSame = false;
if((number1.getNumberator()== number2.getNumberator())&& (number1.getDenominator() == number2.getDenominator())
{
isSame = true;
}
std::cout << isSame;



Nov 6, 2020 at 6:42am
You can overload the equality operator.

https://www.learncpp.com/cpp-tutorial/96-overloading-the-comparison-operators/

PLEASE learn to use code tags, they make reading and commenting on source code MUCH easier.

http://www.cplusplus.com/articles/jEywvCM9/

HINT: you can edit your post and add code tags.

code tags work much better than bold tags.
Nov 6, 2020 at 8:00am
Also, there's lots of scope within that assessment to avoid more factorization. If two fractions are equal then their product (oops, 'divide', 'inverse' or 'cross' that is) will be 1, and their difference will be 0 and their sum will be twice both of them.
Last edited on Nov 6, 2020 at 8:02am
Nov 6, 2020 at 4:28pm
difference and sum would likely do some sort of common denom logic. cross product == 1 is probably fastest.
Topic archived. No new replies allowed.