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

2021-12-30 00:00:00 inheritance constructor c++ c++11

在使用模板时,我遇到了需要使基类构造函数可从继承的类访问以创建对象以减少复制/粘贴操作.我想通过 using 关键字以与函数案例相同的方式来做到这一点,但那行不通.

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 中,您可以使用继承构造函数(其语法在您的示例 D 中可见).

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

更新:自 4.8 版以来,GCC 中已提供继承构造函数.

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
"; }
};

class B : public A
{
public:
    B() : A() {}
    void init(int) { std::cout << "B
"; }
};

class C : public A
{
public:
    C() : A() {}
    void init(int) { std::cout << "C
"; }
};

class D : public A
{
public:
    D() : A() {}
    using A::init;
    void init(const std::string& s) { std::cout << "D -> " << s << "
"; }
};

int main()
{
    B b; b.init(10);
    C c; c.init(10);
    D d; d.init(10); d.init("a");

    return 0;
}

相关文章