【问题标题】:C++: assignment operator not calledC ++:未调用赋值运算符
【发布时间】: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&amp; i); foo(get_int());
  • 尝试将赋值运算符参数设为常量? void operator=(const TestClass&amp; rhs)

标签: c++ overloading variable-assignment


【解决方案1】:

为什么不涉及 void operator=(TestClass& _rhs)?

因为赋值运算符格式错误。应该是:

void operator=(TestClass const& _rhs)
//                CONST! ^^^^^

您的表单 void operator=(TestClass&amp; _rhs) 将不接受纯右值(临时值),例如从 test_function() 返回的临时值。

因此,您的代码中唯一的有效赋值是void operator=(float _value),这是可能的,因为您的类可以隐式转换为float

【讨论】:

    【解决方案2】:

    您应该为 TestClass 声明不同的 operator=。要么使用

    void operator=(const TestClass& _rhs)
    

    void operator=(TestClass _rhs)
    

    这是因为函数 test_functions 返回一个临时值,您不能临时绑定到非 const 左值引用。这就是选择另一个 operator=(float) 的原因。

    您可以在这里找到重载解析规则:https://riptutorial.com/cplusplus/example/8117/steps-of-overload-resolution

    【讨论】:

      猜你喜欢
      • 2020-02-20
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 2011-12-12
      • 2021-08-10
      • 2017-09-10
      • 2016-04-01
      • 2013-03-30
      相关资源
      最近更新 更多