C++ operator overloading: no known conversion from object to reference?

后端 未结 2 1490
暖寄归人
暖寄归人 2021-01-04 06:54

When I try to compile the following (g++ 4.6.3)

class A {};

A& operator*=( A& a, const A& b )
{
  return a;
}

A operator*( const A& a, cons         


        
相关标签:
2条回答
  • 2021-01-04 07:33

    When you write A( a ), you create a temporary of type A ( a rvalue ) that you copy-construct with a. C++ states that no rvalue could be passed as non const reference. Visual Studio is a bit sloppy about this rule, but gcc and the like enforce it.

    To fix, try this ( which is exactly the same, but you create a lvalue by naming that variable ). More on l- and r-value here

    A operator*( A a, const A& b )
    {
       return a *= b;
    }
    
    0 讨论(0)
  • 2021-01-04 07:40

    Like Lucian said, you cannot bind a temporary object to a non-const reference. The expectance of the compiler is that the object will cease to exist after the expression so it makes no sense to modify it.

    To fix your code, remove the temporary (making the argument const& makes no sense in operator *=):

    A operator*(A a, const A& b)
    {
        return a *= b;
    }
    
    0 讨论(0)
提交回复
热议问题