[英]Why type conversion does not work with += operator?
I wrote the following code as a practice for my OOP exam:我编写了以下代码作为我的 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
}
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.我认为转换为 double 后,运算符“+=”将与 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 Godbolt: https://godbolt.org/z/rnsMf7aYh
I thought that with the conversion to double, the operator '+=' will work with doble.我认为转换为 double 后,运算符“+=”将与 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.问题是操作数b
和c
都是同一类型,因此这里不需要类型转换为double
。 Moreover, since you've not overloaded operator+=
for doble
, it produces the mentioned error.此外,由于您没有为doble
重载operator+=
,它会产生上述错误。
I don't know what else can I do我不知道我还能做什么
To solve this you can overload operator+=
:要解决这个问题,您可以重载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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.