小编kor*_*zck的帖子

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

我有这个代码:

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

c++ this method-chaining

0
推荐指数
1
解决办法
148
查看次数

标签 统计

c++ ×1

method-chaining ×1

this ×1