[英]Pass Parameter to Base Class Constructor while creating Derived class Object
Consider two classes A
and B
考虑两个
A
和B
类
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 B
inherits A
. 现在
B
类继承了A
I want to create an object of B
. 我想创建一个
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. 我知道创建一个派生类对象,也会调用基类构造函数,但这是没有任何参数的默认构造函数。
What i want is that B
to take a parameter (say 5), and pass it on to the constructor of A
. 我想要的是
B
取一个参数(比如5),并将它传递给A
的构造函数。 Please show some code to demonstrate this concept. 请展示一些代码来演示这个概念。
Use base member initialisation: 使用基本成员初始化:
class B : public A
{
public:
B(int a) : A(a)
{
}
~B();
};
B::B(int x):A(x)
{
//Body of B constructor
}
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. 请注意,我之前甚至没有使用“public”访问说明符。 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 constructors at: 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/307648 to understand limitations on constructor inheritance. 您也可以参考https://softwareengineering.stackexchange.com/a/307648来了解构造函数继承的限制。
class A { public: int aval; A级{public:int aval;
A(int a):aval(a){};
~A();
}; };
class B : public A { public: int bval; B级:公共A {public: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 . 在这种情况下,您将为基类和派生类分配值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.