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

kor*_*zck 0 c++ this method-chaining

我有这个代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

5
10
Run Code Online (Sandbox Code Playgroud)

我想add()返回该a对象,以便第二个add()就像(*this).add(5),但这不起作用。不过,b很好(怎么样?)。我预计a是 10,与 相同b

那么,我在哪里错过了隐藏指针的用法呢?我应该怎么做才能将a.add(5).add(5)变为10?m_valuea

Rem*_*eau 6

add()*this 按值返回,因此它返回 的副本*this因此链接add()正在修改副本,而不是原始副本。

add()需要*this 通过引用返回:

Something& add(int value)
{
    m_value += value;
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

更新: a最初m_value设置为 0,然后a.add(5)设置a.m_value为 5,然后返回的副本a。然后<copy>.add(5)设置<copy>.m_value为 10 并返回另一个副本,然后将其分配给b。这就是为什么你看到的a是 5,但却b是 10。