简体   繁体   中英

How can I compare the member variables of two objects in C++?

I have created an class Fraction in C++ that stores the numerator and denominator of a fraction, and has various methods to operate on these numbers. How would I compare the contents of one object to another? My thought was to pass a pointer to the second object to the first object's method that carries out the comparison. Any help would be much appreciated.

您应该简单地重载==运算符。

You can overload operator == , like this:

bool operator==(const Fraction &left, const Fraction &right) {
    // Warning: this check is oversimplified; it may overflow!
    return left.num*right.denom == right.num*left.denom;
}

Now you can do this:

Fraction a(10, 20);
Fraction b(2, 4);
if (a == b) {
    ...
}

General information on operator overloading: link .

Take a look at this. Operator overloading

I recommend that you declare and define the appropriate overloaded operators. The answers at the above link provide you with guidance about how to accomplish that. That will allow you to use operators on class instances (objects) with the same natural syntax that you would use for built in types.

If you are comparing with an object of the same type you can directly implement functions which compare the members even if they are private. If you want to test for equality, inequality and lower than / greater than then I suggest that you overload the appropriate operators:

Operator overloading

If, however, you wish to compare objects of different types then you have a few options. You can implement accessor methods ("getters") and use those in a comparing method, you can change the access rights to those variables (not encouraged) or you can use the friend keyword but use it sparingly.

When should you use 'friend' in C++?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM