C++ 不带C+的继承构造函数+;11

C++ 不带C+的继承构造函数+;11,c++,inheritance,constructor,c++03,C++,Inheritance,Constructor,C++03,上面的链接说: 在C++03中,标准构造函数不能被继承,您需要通过自己调用基本实现来手动一个接一个地继承它们 那么,在没有C++11的情况下,如何做到这一点并绕过它呢 #include <iostream> using namespace std; class A { public: int x; explicit A(int _x) { x = _x; } }; class B:A { p

上面的链接说:

在C++03中,标准构造函数不能被继承,您需要通过自己调用基本实现来手动一个接一个地继承它们

那么,在没有C++11的情况下,如何做到这一点并绕过它呢

#include <iostream>

using namespace std;


class A {   
    public:
        int x;
        explicit A(int _x) {
        x = _x;
        }
};

class B:A {
    public:
    explicit B(int x) : A(x) { 

    }
};


int main(int argc, char** argv) {
     A a(10);
     B b(11);

     cout << a.x;
     cout << b.x;

return 0;
#包括
使用名称空间std;
A类{
公众:
int x;
显式A(int_x){
x=x;
}
};
B类:A{
公众:
显式B(intx):A(x){
}
};
int main(int argc,字符**argv){
A(10);
B(11);

cout要修复显示的代码:

  • class B:A
    替换为
    class B:public A
    ,以访问
    main
    中的
    A::x


  • Add
    Kamil:这意味着在派生的C++03类中,如果你想公开这些构造函数,就必须为每个基类构造函数编写一个包装器。我想,不可用的注释……我应该使用C++11吗?@KamilWiśniewski-这很简单。如果可以,那么当然可以。@Kamil-链接上的第二个答案显示了exactly在C++03中你必须如何做到这一点Kamil:你应该发布你的非工作代码,解释你期望的(以及为什么),以及它实际上做了什么。然后问题是如何实现你期望和想要的,以及为什么你的非工作代码没有做到这一点。
    
    #include <iostream>
    #include <utility>    // std::forward
    using namespace std;
    
    class A
    {
    public:
        int x;
        explicit A(int _x): x{ _x } {}
    };
    
    class B:
        public A
    {
    public:
        template< class... Args >
        explicit B( Args&&... args) : A{ forward<Args>( args )... } {}
    };
    
    auto main()
        -> int
    {
        A a{ 10 };
        B b{ 11 };
    
        cout << a.x << endl;
        cout << b.x << endl;
    }
    
    class B:
        public Constructor_arg_forwarder_<A>
    {
    public:
        template< class Args >
        explicit B( Args const& args)
            : Constructor_arg_forwarder_<A>( args )
        {}
    };
    
    int main()
    {
        A a( args( 10 ) );
        B b( args( 11 ) );
    
        cout << a.x << endl;
        cout << b.x << endl;
    }