为什么这种链接方法不起作用
Why is this chaining method not working?
这是一个简单的计数器。默认情况下,调用方法 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
调用的效果。
相关文章:
- 基本加密和解密方法不起作用 C++ 11.
- 结构/方法不起作用
- 将字符数组设置为彼此相等的方法不起作用
- ConvertToReferencePoint 方法不起作用,获取作业参数的 NULL (HyperV 2016)
- 为什么方法不起作用?
- C boost :: bimap insert()方法不起作用
- 为什么我的将向量保存到文件然后再次读出的方法不起作用?
- 为什么这种交换方法不起作用
- Qt. 方法显示文本() 如果我在 QStyledItemDelegate 中定义了 paint() 方法不起作用
- 非递归二进制树插入()方法不起作用
- C++中的Friend方法不起作用
- 为什么这种删除文件夹中文件的方法不起作用?
- 二叉树递归插入方法不起作用
- CGI POST方法不起作用
- 为什么我的 pow 方法不起作用?
- 类方法不起作用
- 使用ctypes从Python调用C++方法不起作用
- C++虚拟方法不起作用
- 为什么用double&&初始化对象方法不起作用?
- 使用虚拟重写基类方法不起作用