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

后端 未结 2 1504
暖寄归人
暖寄归人 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: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;
    }
    

提交回复
热议问题