为什么这种链接方法不起作用

Why is this chaining method not working?

本文关键字:方法 不起作用 链接 为什么      更新时间:2023-10-16

这是一个简单的计数器。默认情况下,调用方法 add 以将私有变量count递增 1。我从函数返回 Counter 类,以便它可以被链接,但是当我查看输出时,当我期望它是 3 时,它给了我 1,因为我调用了 add 三次。

#include <iostream>
#include <vector>
using std::cout;
class Counter {
    public:
        Counter() : count(0) {}
        Counter add() {
            ++count; return *this;
        }
        int getCount() {
            return count;
        }
    private:
        int count;
};
int main() {
    Counter counter;
    counter.add().add().add();
    cout << counter.getCount();
}

链接习语的整个思想是基于在每个链接调用中访问相同的原始对象。这通常是通过从每个修改方法返回对原始对象的引用来实现的。这就是您的add应该如何声明

    Counter &add() { // <- note the `&`
        ++count; return *this;
    }

这样,链式表达式中每个add应用程序都将修改相同的原始对象。

在原始代码中,从 add 返回原始对象的临时副本。因此,每个额外的add应用程序(在第一个应用程序之后)都在临时副本上工作,修改该副本并生成另一个临时副本。所有这些临时副本在完整表达式结束时消失得无影无踪。因此,除了第一个调用之外,您永远不会看到任何add调用的效果。