【问题标题】:expression must be a modifiable lvalue in my class表达式必须是我班级中的可修改左值
【发布时间】:2014-09-27 11:51:30
【问题描述】:

我知道这意味着什么,但在我的情况下,我不明白为什么我的 IDE 会为此大喊大叫。

Rational operator*(const Rational& that1, const Rational& that2)
{
    Rational temp(that1);
    temp.getNom() *= that2.getNom();
    temp.getDenom() *= that2.getDenom();
    return temp;
}

int Rational::getNom() const
{
    return m_iNom / gcd(m_iNom, m_iDenom);
}
int Rational::getDenom() const
{
    return m_iDenom / gcd(m_iNom, m_iDenom);
}

float Rational::gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}

m_iNom 和 m_iDenom 是 Rational 类中的私有数据成员。

我得到'表达式必须是可修改的左值':

temp.getNom() *= that2.getNom();
temp.getDenom() *= that2.getDenom();

【问题讨论】:

    标签: c++ lvalue


    【解决方案1】:

    您不能影响函数或方法返回的值。

    temp.getNom() *= that2.getNom(); 就像temp.getNom() = temp.getNom() * that2.getNom();

    就像写2 = 2 * 3 和设置2 = 5 一样……没有意义!

    【讨论】:

    • 如果我想返回 nom 和 denom 并通过函数调用来更改它,就像我当时在这里所做的那样,我会怎么做,我必须制作 setter 吗?
    • 调用 setter (.setNom ?) 或在允许的情况下直接访问该字段。
    • 希望我可以在没有二传手的情况下做到这一点,但好的,谢谢您的解释
    【解决方案2】:

    正如编译器所说,您不能分配给返回值。
    即使您可以分配返回值,成员变量也不会受到影响—— 访问器返回成员变量的值,而不是实际变量。

    这样做的惯用方法是首先将operator *= 实现为成员:

    Rational& operator *= (const Rational& that)
    {
        m_iNom *= that.m_iNom;
        m_iDenom *= that.m_iDenom;
        return *this;
    }
    

    然后用它来实现*:

    Rational operator*(const Rational& that1, const Rational& that2)
    {
        Rational result(that1);
        result *= that2;
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 2021-09-17
      • 2014-12-15
      • 2014-12-20
      • 2015-09-19
      • 2016-05-09
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多