简体   繁体   中英

Why type conversion does not work with += operator?

I wrote the following code as a practice for my OOP exam:

#include <iostream>
using namespace std;

class doble
{
public:
    doble(double D):d(D){}
    inline operator double(){return d;}
private:
    double d;
};

int main()
{
    doble a = 1.5, b = 10.5;
    doble c = 5.25, d = c;
    cout << c / d * b + b * c - c * c / b + b / c << endl; //65

    d = a = b += c;
    cout << d <<" "<< a <<" "<< b <<" "<< c << endl; //15,75 15,75 15,75 5,25
}

I get an error in the line with the operator '+=' that says: 'no operator "+=" matches these operands'. I don't know what else can I do because the overloading of arithmetic operators, assignment, insertion, or the use of friendly functions is not allowed in this exercise.

Thank you!

I thought that with the conversion to double, the operator '+=' will work with doble.

Your example works if you defined the operator += properly.

    doble& operator += ( const doble& rhs ) {
        d += rhs.d;
        return *this;
    }

Produces

Program stdout
65
15.75 15.75 15.75 5.25

Godbolt: https://godbolt.org/z/rnsMf7aYh

I thought that with the conversion to double, the operator '+=' will work with doble.

The problem is that both of the operands b and c are of the same type so there is no type conversion to double required here. Moreover, since you've not overloaded operator+= for doble , it produces the mentioned error.


I don't know what else can I do

To solve this you can overload operator+= :

#include <iostream>


class doble
{
public:
    doble(double D):d(D){}
    inline operator double(){return d;}
    //overload operator+=
     doble& operator+=(const doble& rhs) 
    {                           
        /* addition of rhs to *this takes place here */
        d+=rhs.d;
        return *this; // return the result by reference
    }
private:
    double d;
};

int main()
{
    doble b = 10.5;
    doble c = 5.25;
    b += c;
    std::cout << b << c;
}

Demo

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