简体   繁体   English

如何声明默认构造函数

[英]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.

相关问题 当构造函数用作默认参数时,如何定义和声明结构? - How to define and declare a struct when the constructor is used for a default argument? 如何在派生类中声明复制构造函数,而基类中没有默认构造函数? - How to declare copy constructor in derived class, without default construcor in base? “何时”编译器是否隐式声明了默认构造函数? - “When” does the compiler implicitly declare a default constructor? 声明对象而不调用默认构造函数 - Declare object without calling default constructor 如何声明一个对象但不运行构造函数? - How to declare an object but not run the constructor? 如何声明一个类没有默认构造函数的对象数组? - How do I declare an array of objects whose class has no default constructor? 如何使用C ++中的默认构造函数定义和声明变量? - How do I make define and declare a variable using the default constructor in C++? 将默认生成的复制构造函数与 Q_DECLARE_METATYPE 一起使用 - Using default generated copy constructor with Q_DECLARE_METATYPE 类型是否需要默认构造函数才能声明它的数组? - Does a type require a default constructor in order to declare an array of it? 声明空/默认构造函数的几种方法之间的差异 - Differences between several ways to declare an empty/default constructor
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM