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

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

提交回复
热议问题