使用C ++基类构造函数?

编程入门 行业动态 更新时间:2024-10-22 13:44:10
本文介绍了使用C ++基类构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用模板时,我遇到了一个需要使一个基类构造函数可以从继承类创建对象,以减少复制/粘贴操作。 我想通过使用关键字以相同的方式通过函数case来执行此操作,但不起作用。

While working with templates I ran into a need to make a base class constructors accessible from inherited classes for object creation to decrease copy/paste operations. I was thinking to do this through using keyword in same manner with functions case, but that not work.

class A { public: A(int val) {} }; class B : public A { }; class C : public A { public: C(const string &val) {} }; class D : public A { public: D(const string &val) {} using A::A; // g++ error: A::A names constructor }; void main() { B b(10); // Ok. (A::A constructor is not overlapped) C c(10); // error: no matching function to call to 'C::C(int)' }

所以我的问题:有没有任何方法来导入一个基类构造函数后继承类中的新的类被声明?

So my question: Is there any way to import a base class constructors after new ones in inherited class been declared?

或者只有一个替代声明新

Or there is only one alternative to declare new constructors and call a base ones from initializer list?

推荐答案

首选初始化:

class C : public A { public: C(const string &val) : A(anInt) {} };

在C ++ 11中,可以使用继承构造函数code> D )。

In C++11, you can use inheriting constructors (which has the syntax seen in your example D).

更新: GCC自4.8版开始提供继承构造函数。

Update: Inheriting Constructors have been available in GCC since version 4.8.

如果你没有发现初始化有吸引力(例如,由于你的实际情况下的可能性的数量),那么你可能喜欢这种方法对于一些TMP结构:

If you don't find initialization appealing (e.g. due to the number of possibilities in your actual case), then you might favor this approach for some TMP constructs:

class A { public: A() {} virtual ~A() {} void init(int) { std::cout << "A\n"; } }; class B : public A { public: B() : A() {} void init(int) { std::cout << "B\n"; } }; class C : public A { public: C() : A() {} void init(int) { std::cout << "C\n"; } }; class D : public A { public: D() : A() {} using A::init; void init(const std::string& s) { std::cout << "D -> " << s << "\n"; } }; int main() { B b; b.init(10); C c; c.init(10); D d; d.init(10); d.init("a"); return 0; }

更多推荐

使用C ++基类构造函数?

本文发布于:2023-10-31 07:32:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545443.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!