C ++方法链接类 [英] C++ Method chaining with classes
问题描述
我试图做方法链接,但是,而不是使用方法在Foo我想要一个类的构造函数(它继承自基类):
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();
C ++ 11?还有,有没有一种方法,我可以集成这个标准,或者我必须创建一个方法在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"?
编辑:
class Bar {
public:
Bar() {
}
Bar& Options() {
cout << "sf";
return *this;
}
};
class Foo : public Bar {
public:
Foo() {
}
};
然后在main:
code> Foo F = Foo()。Options();
Foo F = Foo().Options();
推荐答案
问题是非法的,因为 Bar :: Options()
返回对 Bar
的引用,将 Bar
转换为 Foo
对象。
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.
这篇关于C ++方法链接类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!