【发布时间】:2021-03-14 19:49:00
【问题描述】:
我有以下代码。
当我写o1 = o2 时,void operator=(TestClass& _rhs) 被调用。没关系。
但是当我执行o1 = test_function(); 时,首先调用operator float(),然后调用void operator=(float _value)。逻辑上是对的,但是为什么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();
}
【问题讨论】:
-
在我看来像是复制省略。
-
你过于复杂了:
void foo(int& i); foo(get_int()); -
尝试将赋值运算符参数设为常量?
void operator=(const TestClass& rhs)
标签: c++ overloading variable-assignment