C++ 创建派生类对象时将参数传递给基类构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16585856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:28:58  来源:igfitidea点击:

Pass Parameter to Base Class Constructor while creating Derived class Object

c++oopconstructor

提问by CodeCrusader

Consider two classes Aand B

考虑两个类AB

class A
{
public:
    A(int);
    ~A();
};

class B : public A
{
public:
    B(int);
    ~B();
};


int main()
{
    A* aobj;
    B* bobj = new bobj(5);    
}

Now the class Binherits A.

现在该类B继承了A.

I want to create an object of B. I am aware that creating a derived class object, will also invoke the base class constructor , but that is the default constructor without any parameters.

我想创建一个对象B。我知道创建派生类对象也会调用基类构造函数,但这是没有任何参数的默认构造函数。

What i want is that Bto take a parameter (say 5), and pass it on to the constructor of A. Please show some code to demonstrate this concept.

我想要的是B接受一个参数(比如 5),并将它传递给A. 请展示一些代码来演示这个概念。

回答by Bathsheba

Use base member initialisation:

使用基本成员初始化:

class B : public A
{
public:
    B(int a) : A(a)
    {
    }
    ~B();
};

回答by SomeWittyUsername

B::B(int x):A(x)
{
    //Body of B constructor
}

回答by Mandeep Singh

If you are using your derived class constructor just to pass arguments to base class then you can also do it in a shorter way in C++11:

如果您使用派生类构造函数只是将参数传递给基类,那么您也可以在 C++11 中以更短的方式进行:

class B : public A
{
    using A::A;
};

Note that I have not even used "public" access specifier before it. This is not required since inherited constructors are implicitly declared with same access level as in the base class.

请注意,在它之前我什至没有使用过“公共”访问说明符。这不是必需的,因为继承的构造函数是隐式声明的,其访问级别与基类中的访问级别相同。

For more details, please refer to section Inheriting constructorsat: https://en.cppreference.com/w/cpp/language/using_declaration

有关更多详细信息,请参阅继承构造函数部分:https: //en.cppreference.com/w/cpp/language/using_declaration

Also you may refer to https://softwareengineering.stackexchange.com/a/307648to understand limitations on constructor inheritance.

您也可以参考https://softwareengineering.stackexchange.com/a/307648以了解构造函数继承的限制。

回答by Wilson

class A { public: int aval;

A类{公共:int aval;

A(int a):aval(a){};
~A();

};

};

class B : public A { public: int bval;

B 类:公共 A { 公共:int bval;

B(int a,int b):bval(a),A(b){};
~B();

};

};

int main() {

int main() {

  B *bobj = new bobj(5,6);
//or 
  A *aobj=new bobj(5,6); 

}

}

In this case you are assigning the values for base class and derived class .

在这种情况下,您正在为基类和派生类分配值。