我如何使用隐藏的 *this 指针?

How do i use hidden *this pointer?

我有这个代码:

class Something
{
private:
    int m_value = 0;
public:
    Something add(int value)
    {
        m_value += value;
        return *this;
    }
    int getValue()
    {
        return m_value;
    }

};

int main()
{
    Something a;
    Something b = a.add(5).add(5);
    cout << a.getValue() << endl;
    cout << b.getValue() << endl;
}

输出:

5
10

我想要 add() 到 return a 对象,这样第二个 add() 就像 (*this).add(5),但这不起作用。但是,b 很好(怎么样?)。我预计 a 为 10,与 b.

相同

那么,我哪里遗漏了隐藏指针的用法呢?我应该怎么做才能让 a.add(5).add(5)am_value 更改为 10?

add() 是 returning *this by value,所以它是 returning 一个 *this 的副本,因此链式 add() 正在修改副本,而不是原始文件。

add() 需要 return *this 通过引用 代替:

Something& add(int value)
{
    m_value += value;
    return *this;
}

更新: a 最初将 m_value 设置为 0,然后 a.add(5)a.m_value 设置为 5,然后 return是 a副本。然后 <copy>.add(5)<copy>.m_value 设置为 10 和 return 另一个 copy,然后将其分配给 b。这就是为什么您看到 a 是 5 而 b 是 10.