命名构造函数习惯用法和继承
我有一些类,其中有一些 命名构造函数 。当我继承它们时,我应该如何继承构造函数?问题是它们返回基类的对象而不是子类的对象。
附带问题:我可以使用 C++0x “using” 来减少样板代码量吗?
I have a few classes with a few named constructors. When I inherit from them, how should I inherit the constructors? The problem is that they return objects of base class and not of the child class.
Side question: can I use C++0x "using" to reduce the amount of boilerplate code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这可以让你做类似的事情
Which allows you to do things like
您既不继承“经典”构造函数,也不继承“命名”构造函数。您应该为每个派生类创建特定的构造函数。
下面是一个示例,说明如何将命名构造函数与继承一起使用:
Neither do you not inherit "classic" constructors, nor you inherit "named" constructors. You should create specific constructors for each derived class.
Here's an example, how named constructor can be used with inheritance:
命名 ctor 是一个习语,它们不是真正的构造函数。严格来说,命名构造函数依赖于静态函数。继承需要
虚拟
函数。现在,非成员不能是虚拟的,因此排除了静态虚拟函数的想法。using
声明要求编译器继承全部或无基类构造函数。所以,是的,他们可以在某种程度上简化您的代码。但是,你们所有的编译器都支持 C++0x 吗?Named ctor is an idiom, they are not real constructors. Strictly speaking, named ctors depend on
static
functions. Inheritance requiresvirtual
functions. Now, non-members cannot be virtual, hence the idea of havingstatic virtual
functions is ruled out.The
using
declaration asks the compiler to inherit all-or-none of the base class ctors. So, yes in a way they can simplify your code. However, do all your compilers support C++0x?我找到了(几乎)完美的解决方案!
它编译:D
I found (almost) perfect solution!
And it compiles :D