方法链包括类构造函数 [英] method chaining including class constructor

查看:284
本文介绍了方法链包括类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中实现方法链接,如果一个类的构造函数调用是一个单独的语句,例如:

  Foo foo; 

foo.bar()。baz();

但是一旦构造函数调用成为方法链的一部分,编译器就会抱怨 。代替。。紧接在构造函数调用之后:

  Foo foo()。 



现在我想知道如果这在C ++中是可能的。这是我的测试类:

  class Foo 
{
public:
Foo
{
}

Foo& bar()
{
return * this;
}

Foo& baz()
{
return * this;
}
};我还在C ++中找到了一个fluent interfaces的例子( http://en.wikipedia.org/wiki/Fluent_interface#C.2B.2B ),似乎正是我在寻找。

解决方案

您忘记了 Foo 对象。尝试:

  Foo foo = Foo()。bar()。baz 


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.

解决方案

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

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

这篇关于方法链包括类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆