如果类中有类型转换函数,且运算符重载函数中使用了引用,需要使用
const
申明为常引用,否则可能会遇到cannot bind non-const lvalue reference of type ‘&xx’ to an rvalue of type ‘xx’
例子,复数相加,不使用
const
,后面的变量num
被转换为Complex
类时,属于右值,不能直接和非常引用
绑定,报错。
代码: 全选
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(){real = 0; imag = 0;}
Complex(double r){real = r; imag = 0;}
Complex(double r, double i){real = r; imag = i;}
friend Complex operator+(const Complex &, const Complex &);
friend istream& operator>>(istream &, Complex &);
friend void display(Complex &);
private:
double real;
double imag;
};
Complex operator+(const Complex &c1, const Complex &c2)
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
istream& operator>>(istream& input, Complex& c1)
{
input >> c1.real >> c1.imag;
return input;
}
void display(Complex &c1)
{
cout << c1.real;
if (c1.imag < 0)
{
cout << "-" << c1.imag << "i" << endl;
}
else
{
cout << "+" << c1.imag << "i" << endl;
}
}
int main(void)
{
Complex c1, c2;
cout << "请输入实部和虚部" << endl;
cin >> c1;
display(c1);
cout << "用一个整数去加它" << endl;
double num;
cin >> num;
c1 = num + c1;
display(c1);
cout << "用它去加一个整数" << endl;
cin >> num;
c1 = c1 + num;
display(c1);
cout << "它和另一个复数1+2i相加" << endl;
c2 = Complex(1, 2);
c2 = c2 + c1;
display(c2);
return 0;
}
引用
还是值
的话,把上面代码中的Complex operator+
改为Complex& operator+
,同样报cannot bind non-const lvalue reference of type ‘&xx’ to an rvalue of type ‘xx’
的错误,因此搞清楚到底返回什么很重要,引用也不要盲目的使用。因此上面的例子,我们还可以改为如下实现
代码: 全选
9c9
< friend Complex operator+(const Complex &, const Complex &);
---
> friend Complex operator+(Complex, Complex);
18c18
< Complex operator+(const Complex &c1, const Complex &c2)
---
> Complex operator+(Complex c1, Complex c2)
代码: 全选
class X
{
public:
X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
{ // but often is, to modify the private members)
/* addition of rhs to *this takes place here */
return *this; // return the result by reference
}
// friends defined inside class body are inline and are hidden from non-ADL lookup
friend X operator+(X lhs, // passing lhs by value helps optimize chained a+b+c
const X& rhs) // otherwise, both parameters may be const references
{
lhs += rhs; // reuse compound assignment
return lhs; // return the result by value (uses move constructor)
}
};
参考资料:
1. Operator overloading C++ reference or value
2. cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*'
3. Common operators to overload