【问题标题】:operator= for mismatched typesoperator= 用于不匹配的类型
【发布时间】:2020-12-03 23:42:15
【问题描述】:

我有下面的代码,我试图为我的类和一个字符创建一个 operator=。该类有一个 char 的构造函数。

当我调用 = 运算符时,它会进入类并正确分配类 b,但是当它返回时 byte1 没有更新。我不确定为什么会这样。

我班的一部分:

Byte operator=(unsigned char lhs)
{
    Byte b(lhs);
    return b;
}

int main()
{
    unsigned char c1{ 'a' };
    Binary::Byte byte1;
    byte1 = c1;
}

【问题讨论】:

  • 我们无法使用“您的课程的一部分”来调试您的程序 :-)
  • 问题是operator= 没有变异*this。您正在operator= 中创建一个新的Byte 对象,而不是修改您已经拥有的对象,并且在main 中对operator= 的调用会丢弃新对象(因为您不使用的返回值byte1 = c1)。 operator= 通常应该 1) 实际上改变*this,2) 返回Byte&(一般为CurrentClass&),3) 总是return *this;
  • HTNW,谢谢!这正是问题所在。
  • 有人请回答或删除此问题。

标签: c++ class return operator-overloading


【解决方案1】:

正如@HTNW 所说,我没有返回 *this。应该是:

Byte operator=(unsigned char lhs)

    {
        Byte b(lhs);
        *this = b;
        return *this;
    }

【讨论】:

    猜你喜欢
    • 2015-09-09
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    相关资源
    最近更新 更多