[英]how to declare default constructor
I have a Base class that I can't modify the source code. 我有一个无法修改源代码的基类。 I make a derived class from it and I am trying to make a no-argument constructor for this derived class.
我从中得到一个派生类,并且试图为此派生类创建一个无参数的构造函数。 The problem is that I can't define the constructor for two reasons: There is not a non-argument constructor defined for the base class to use it.
问题是,由于两个原因,我无法定义构造函数:没有为基类定义使用它的非参数构造函数。 I can't pass a default value for the constructor of the base.
我无法传递基础构造函数的默认值。
class base
{
public:
base (A arg)
{
}
};
class derived : public base
{
public:
derived () : base (arg) //ERROR
{
}
};
Is there a solution to define a non-argument constructor for the derived class? 有没有为派生类定义非参数构造函数的解决方案? Cordialement,
Cordialement,
Since you cannot change the base class the only option left is to pass an argument to its constructor. 由于您无法更改基类,因此剩下的唯一选择就是将参数传递给其构造函数。 You can do this quite easily by constructing a temporary instance of
A
and passing it to the base class in your ctor initialized list of derived classes. 通过构造
A
的临时实例并将其传递给派生类的ctor初始化列表中的基类,您可以非常容易地做到这一点。
derived::derived () : base (A())
{
}
In the code above base(A())
will create a temporary instance of A
and pass it to the constructor of base
. 在上面的代码中,
base(A())
将创建A
的临时实例,并将其传递给base
的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.