gpt4 book ai didi

c++ - 从命名对象的构造函数链式调用成员函数

转载 作者:可可西里 更新时间:2023-11-01 17:53:25 26 4
gpt4 key购买 nike

首先,我不是在谈论 C++11 构造函数链接,也就是构造函数委托(delegate)。

类成员函数可以返回对自身(类)的引用,因此可以链接函数调用。 (例如 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;
}

最佳答案

我认为这是 Almost Always Auto 的优势之一风格。如果你有写作的习惯:

auto a = foo{3};

然后你可以在没有不一致的情况下进行链式调用:

auto a = foo{3}.inc();

关于c++ - 从命名对象的构造函数链式调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39682632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com