用于不匹配类型的operator =

问题描述

我在下面的代码中尝试为我的课程和一个字符创建一个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;
}

解决方法

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

Byte operator=(unsigned char lhs)

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