c++ 为什么类型转换不能与+=运算符一起使用?

8ulbf1ek  于 2023-01-28  发布在  其他
关注(0)|答案(2)|浏览(115)

我编写了以下代码作为OOP考试的练习:

#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
}

我在包含运算符"+="的行中得到一个错误,该错误表示:'没有运算符"+="匹配这些运算符'。我不知道还能做什么,因为本练习不允许重载算术运算符、赋值、插入或使用友好函数。
谢谢大家!
我认为在转换为double时,运算符"+="将与doble一起工作。

3qpi33ja

3qpi33ja1#

如果正确定义了运算符+=,则示例可以正常工作。

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

生产

Program stdout
65
15.75 15.75 15.75 5.25

神箭:https://godbolt.org/z/rnsMf7aYh

sqserrrh

sqserrrh2#

我认为在转换为double时,运算符“+=”将与doble一起工作。

问题是操作数bc是相同的类型,所以这里不需要类型转换到double,而且,因为你没有重载operator+=来替换doble,所以它产生了上面提到的错误。

我不知道我还能做什么
解决这个问题,可以重载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

相关问题