C++:成员二元加运算符如何工作?
C++: How member binary plus operator works?
我们有一个class(假设函数中有一些操作,但构造函数是默认的):
class X
{
public:
X& operator=(const X& rhs){}
const X& operator+(const X& rhs) const {}
const X& operator+(int m) {}
};
X a, b, c;
Q1:为什么允许a = a + 5 + c;
而不允许a = b + c + 5;
?我们有:
Error C2679 binary '+': no operator found which takes a right-hand
operand of type 'int' (or there is no acceptable conversion).
Q2:为什么(c = a + a) = b + c;
以b+c运算开头,而不是a+a运算? (我在调试时发现了这一点)。
P.S。只是理论问题。
Why is a = a + 5 + c; allowed and a = b + c + 5; is not?
const X& operator+(int m) {} 不是 const 函数,+ 运算符中的 return 是 const X。将其设为 const 函数,它会正常工作; (除了return在这个操作之后引用很奇怪)
我们有一个class(假设函数中有一些操作,但构造函数是默认的):
class X
{
public:
X& operator=(const X& rhs){}
const X& operator+(const X& rhs) const {}
const X& operator+(int m) {}
};
X a, b, c;
Q1:为什么允许a = a + 5 + c;
而不允许a = b + c + 5;
?我们有:
Error C2679 binary '+': no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion).
Q2:为什么(c = a + a) = b + c;
以b+c运算开头,而不是a+a运算? (我在调试时发现了这一点)。
P.S。只是理论问题。
Why is a = a + 5 + c; allowed and a = b + c + 5; is not?
const X& operator+(int m) {} 不是 const 函数,+ 运算符中的 return 是 const X。将其设为 const 函数,它会正常工作; (除了return在这个操作之后引用很奇怪)