使用模板时,我遇到了一个需要使一个基类构造函数可以从继承类创建对象,以减少复制/粘贴操作。 我想通过使用关键字以相同的方式通过函数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 ++基类构造函数?
发布评论