简体   繁体   中英

Can I only have const overloaded operator member function?

I'm implementing a fraction class, and need to overload arithmetic operators. The problem is, can I only implement a const version.

For example, addition:

Fraction operator+( const Fraction& other ) const;

Since both non-const, and const Fraction objects can call this function, do I still need to have an non-const operator+ member function?

const member functions can be called on non- const objects, so no, you don't need a non- const overload.

Fraction a, b;
Fraction c = a + b; // no problem

In general, this kind of problem is better solved with a member operator+= and a nonmember operator+ , like this:

class Fraction {
public:
    const Fraction& operator+=(const Fraction&);
};

Fraction operator+(const Fraction& lhs, const Fraction& rhs) {
    Fraction res(lhs);
    res += rhs;
    return res;
}

No. You can call const methods over non- const objects, exactly as you can have const references bind to non- const objects. IOW, you can always pass an object that you can modify to code that promises not to modify it - there's no loss of safety. The opposite of course is not true - if you have a const object (=> an object you promised not to modify) you cannot pass it to code that doesn't adhere to this promise.

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