C++ Method chaining with classes

拈花ヽ惹草 提交于 2019-12-13 05:15:43

问题


I'm attempting to do method chaining, however, instead of using the Methods in "Foo" I want to a constructor of a class (which is inherited from the base class):

class Bar {

public: 

Bar() {
    std::cout << "This is bar";
}

 };

 class Foo : public Bar {

    public:
    Foo() {
        cout << "This is foo";
    }
 };

So my main would look like the following:

Foo f = Foo().Bar();

Why is this not possible in C++/C++11? Also, is there a way in which I can integrate this standard, or would I have to create an method in "Foo" which calls the constructor to "Bar"?

Edit:

class Bar {
public: 
Bar() {
}

Bar& Options() {
    cout << "sf";
    return *this;
}
 };

class Foo : public Bar {

public:
    Foo() {

    }
  }; 

And then in main:

Foo F = Foo().Options();


回答1:


Your updated question is illegal because Bar::Options() returns a reference to a Bar and you don't provide a way to convert a Bar to a Foo object.



来源:https://stackoverflow.com/questions/18725072/c-method-chaining-with-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!