无法将类型为"类名 &"的非常量左值引用绑定到类型为"类名"的右值
cannot bind non-const lvalue reference of type 'ClassName &’ to an rvalue of type ‘ClassName’
这是我的函数原型:
Rational & operator+=(const Rational &);
这是我课程的一部分:
class Rational
{
public:
Rational(int a = 0, int b = 1) : n(a), d(b) {}
这是我的函数:
Rational & Rational::operator+=(const Rational & r)
{
return (r + *this);
}
我已经做了一个函数来添加两个有理数。 当我尝试编译它时,出现以下错误:
error: cannot bind non-const lvalue reference of type
‘Rational&’ to an rvalue of type ‘Rational’
return (r + *this);
我做错了什么?
你的 operator+ 返回一个新的实例,不是吗?那么,您的退货声明中会发生什么?
-
您尝试返回临时结果(这就是错误消息的内容)。
-
同时,您没有修改此对象,因此违反了 += 语义(不,通过替换表达式的结果,此值应该是,您没有向编译器提供实际意图的丝毫提示。
你知道,更自然的实现是将真正的数学放在 operator+= 中,然后在 operator+ 中重用它,类似于R retVal = a; return a += b;
。
相关文章:
- 有没有一种方法可以在编译时获得作用域类名
- 用C++中的CPerson(类)类型的对象初始化STL矢量
- 错误:需要类名(链表c++)
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- (结构名/类名)不命名类型C++
- 类名后跟括号的类型是什么
- C++ 错误:(类名)未命名类型
- 在子类上调用模板化静态方法时获取类的类型名
- 无法将类型为"类名 &"的非常量左值引用绑定到类型为"类名"的右值
- 类名不命名类型 - 拔掉我的头发
- 无法从 void* 类型转换(类名::)() 以键入 void*(*)(void*)
- 类型“类名”不提供调用运算符.C++
- 错误:"类名"未命名类型
- 为什么即使模板类型被声明为“类”,“类型名”仍然是必需的
- 什么时候不能用“类”代替“类型名”
- 如何在类名careercenter中定义数组类型customers,然后在.cpp文件中定义create, modify
- c++;如何将字符串(类名)转换为类型
- 无法在pthread中从类型void*(类名)(void*)转换为类型void* (*)(void*)
- 类名不声明c++类型