方法链包括类构造函数

发布于 2024-09-02 11:25:36 字数 646 浏览 1 评论 0原文

我正在尝试在 C++ 中实现方法链,如果类的构造函数调用是一个单独的语句,那么这会非常容易,例如:

Foo foo;

foo.bar().baz();

但是一旦构造函数调用成为方法链的一部分,编译器就会抱怨期待“;”代替“.”紧接着构造函数调用之后:

Foo foo().bar().baz();

我现在想知道这在 C++ 中是否真的可行。这是我的测试类:

class Foo
{
public:
    Foo()
    {
    }

    Foo& bar()
    {
        return *this;
    }

    Foo& baz()
    {
        return *this;
    }
};

我还找到了 C++ 中“流畅接口”的示例 (http://en.wikipedia.org/wiki/Fluent_interface#C.2B.2B)这似乎正是我正在寻找的内容。但是,我对该代码遇到了相同的编译器错误。

I'm trying to implement method chaining in C++, which turns out to be quite easy if the constructor call of a class is a separate statement, e.g:

Foo foo;

foo.bar().baz();

But as soon as the constructor call becomes part of the method chain, the compiler complains about expecting ";" in place of "." immediately after the constructor call:

Foo foo().bar().baz();

I'm wondering now if this is actually possible in C++. Here is my test class:

class Foo
{
public:
    Foo()
    {
    }

    Foo& bar()
    {
        return *this;
    }

    Foo& baz()
    {
        return *this;
    }
};

I also found an example for "fluent interfaces" in C++ (http://en.wikipedia.org/wiki/Fluent_interface#C.2B.2B) which seems to be exactly what I'm searching for. However, I get the same compiler error for that code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落叶缤纷 2024-09-09 11:25:36

尝试

// creates a temporary object
// calls bar then baz.
Foo().bar().baz();

Try

// creates a temporary object
// calls bar then baz.
Foo().bar().baz();
时光是把杀猪刀 2024-09-09 11:25:36

您忘记了 Foo 对象的实际名称。尝试:

Foo foo = Foo().bar().baz();

You have forgotten the actual name for the Foo object. Try:

Foo foo = Foo().bar().baz();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文