use*_*689 8 c++ method-chaining chaining c++11
首先,我不是在谈论c ++ 11构造函数链接也就是构造函数委托.
类成员函数可以返回对自身(类)的引用,因此可以链接函数调用.(例如cout <<运算符如何工作以允许链调用.)
在实例化匿名对象时,可以在构造函数之外进行此类链调用.
链调用是否可以从命名对象的构造函数中进行?下面的"foo a"和"foo b"的行不能编译,所以我想知道是否有不同的语法.
#include <iostream>
using namespace std;
class foo {
public:
foo(int x) : val{x} { };
foo& inc() { ++val; return *this; }
int getVal() { return val; };
private:
int val;
};
int main() {
cout << foo(1).inc().getVal() << endl; // prints 2
cout << foo{2}.inc().inc().inc().inc().getVal() << endl; // prints 6
foo a(3).inc(); // error: expected ‘,’ or ‘;’ before ‘.’ token
foo b{4}.inc(); // error: expected ‘,’ or ‘;’ before ‘.’ token
cout << a.getVal() << endl;
cout << b.getVal() << endl;
}
Run Code Online (Sandbox Code Playgroud)
小智 3
您可以获得链接初始化的类似效果:
foo c = foo{5}.inc().inc();
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是,我的编译器将其优化为常量,因此没有性能损失。
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |