[英]C++: assignment operator not called
I have a following code which is below.我有一个下面的代码。
When I write o1 = o2
, void operator=(TestClass& _rhs)
is called.当我写o1 = o2
时, void operator=(TestClass& _rhs)
被调用。 It's ok.没关系。
But when I do o1 = test_function();
但是当我做o1 = test_function();
, first operator float()
is called, then void operator=(float _value)
. ,首先调用operator float()
,然后调用void operator=(float _value)
。 It's logically correct, but why is void operator=(TestClass& _rhs)
not invoked?这在逻辑上是正确的,但是为什么没有调用void operator=(TestClass& _rhs)
呢?
class TestClass
{
public:
TestClass(float _value)
{
value = _value;
}
operator float()
{
return value;
}
void operator=(float _value)
{
}
void operator=(TestClass& _rhs)
{
}
private:
float value;
};
TestClass test_function()
{
TestClass result = 0;
return result;
}
int main()
{
std::cout << "Hello World!\n";
TestClass o1(1), o2(1);
o1 = o2;
o1 = test_function();
}
why void operator=(TestClass& _rhs) is not involved?为什么不涉及 void operator=(TestClass& _rhs) ?
Because that assignment operator is malformed.因为该赋值运算符格式错误。 It should be:它应该是:
void operator=(TestClass const& _rhs)
// CONST! ^^^^^
Your form, void operator=(TestClass& _rhs)
will not accept prvalues (temporaries), like the temporary returned from test_function()
.您的表单void operator=(TestClass& _rhs)
将不接受纯右值(临时值),例如从test_function()
返回的临时值。
So, the only valid assignment in your code is void operator=(float _value)
, which is possible because your class can implicitly convert to a float
.因此,您的代码中唯一有效的赋值是void operator=(float _value)
,这是可能的,因为您的 class 可以隐式转换为float
。
You should declare operator= differently for TestClass.您应该为 TestClass 声明不同的 operator=。 Either use要么使用
void operator=(const TestClass& _rhs)
or或者
void operator=(TestClass _rhs)
This is because function test_functions returns a temporary value, and you cannot bind temporarily to a non-const lvalue reference.这是因为 function test_functions 返回一个临时值,并且您不能临时绑定到非常量左值引用。 This is why the other operator=(float) is selected.这就是选择另一个 operator=(float) 的原因。
You may find overload resolution rules here: https://riptutorial.com/cplusplus/example/8117/steps-of-overload-resolution您可以在此处找到重载解决规则: https://riptutorial.com/cplusplus/example/8117/steps-of-overload-resolution
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.