C ++运算符重载:没有从对象到引用的已知转换? [英] C++ operator overloading: no known conversion from object to reference?
问题描述
当我尝试编译以下(g ++ 4.6.3)
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, const A& b )
{
return A( a ) *= b;
}
int main( int, char*[] )
{
A a, b;
a = a*b;
return 0;
}
我得到错误
/tmp/test.cxx: In function ‘A operator*(const A&, const A&)’:
/tmp/test.cxx:14:20: error: no match for ‘operator*=’ in ‘(* & a) *= b’
/tmp/test.cxx:14:20: note: candidate is:
/tmp/test.cxx:6:1: note: A& operator*=(A&, const A&)
/tmp/test.cxx:6:1: note: no known conversion for argument 1 from ‘A’ to ‘A&’
这让我很困惑 - 如何从一个类转换为该类的引用不知道?
This puzzles me - how can a conversion from a class to a reference to that class not be known?
更改类A的声明如下所示:
Changing the declaration of class A as follows does not have any effect:
class A
{
public:
A() {}
A( const A& ) {}
};
同样的错误。
推荐答案
像Lucian说的,你不能将一个临时对象绑定到一个非临时对象上, const引用。编译器的期望是,对象将在表达式之后停止存在,所以修改它是没有意义的。
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.
要修复你的代码,删除临时在 operator * =
)中的参数 const&
没有意义:
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;
}
这篇关于C ++运算符重载:没有从对象到引用的已知转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!