【问题标题】:Derived Class Constructor Calls派生类构造函数调用
【发布时间】:2012-11-06 22:11:45
【问题描述】:

如果我有一个基类:

class Base{
  ...
};

还有一个派生类

class Derived : public Base{
  ...
}

这个派生类是否总是调用基类的默认构造函数?即不带参数的构造函数?例如如果我为基类定义一个构造函数:

Base(int newValue);

但是我没有定义默认构造函数(无参构造函数):

Base();

(我知道这只是一个声明而不是定义) 我得到一个错误,直到我定义了不带参数的默认构造函数。这是因为基类的默认构造函数是被派生类调用的吗?

【问题讨论】:

  • 您可以通过使基类中的默认构造函数打印屏幕独有的内容来进行检查。这是检查此类内容的好方法,您可以从中学习!

标签: c++ inheritance constructor derived-class base-class


【解决方案1】:

是的,默认情况下会调用默认构造函数。您可以通过显式调用非默认构造函数来解决此问题:

class Derived : public Base{
    Derived() : Base(5) {}
};

这将调用带有参数的基构造函数,您不再需要在基类中声明默认构造函数。

【讨论】:

    【解决方案2】:

    调用默认构造函数的原因是,如果您创建了任何对象并且在该实例中您没有传递参数(您可能希望稍后在程序中初始化它们)。这是最普遍的情况,这就是为什么需要调用默认构造函数的原因。

    【讨论】:

      【解决方案3】:

      默认情况下编译器提供三个默认值:

      1. 默认(无参数)Ctor

      2. 复制代码

      3. 赋值运算符

      如果您自己提供参数化 Ctor 或 Copy Ctor,则编译器不会提供默认 Ctor,因此您必须明确编写 Default Ctor。

      当我们创建一个 Derived 类对象时,它默认搜索 Base 的默认 Ctor,如果我们没有提供它,那么编译器会抛出错误。但是我们可以让 Derived 类 Ctor 调用我们指定的 Base Ctor。

      class Base {
      public:
      Base(int x){}
      };
      
      class Derived {
      public:
      Derived():Base(5){}             //this will call Parameterized Base Ctor
      Derived(int x):Base(x){}        //this will call Parameterized Base Ctor
      }
      

      【讨论】:

        【解决方案4】:

        是的,默认情况下会调用默认构造函数。但是如果你的基类有参数化构造函数,那么你可以通过两种方式调用非默认构造函数。:

        option 1: by explicitly calling a non-default constructor:
        
        class Derived : public Base{
        Derived() : Base(5) {}
        };
        

        选项 2:

        in base class constructor set the parameter default value to 0, so it will 
         act as default as well as paramterized constructor both
        
        for example:
        
        class base
        { public:
        base(int m_a =0){} 
        };
        
         class Derived
         { public:
         Derived(){}
        };
        

        上述方法对于参数化构造函数调用和默认构造函数调用都可以正常工作。

        【讨论】:

          猜你喜欢
          • 2016-07-19
          • 2018-07-21
          • 1970-01-01
          • 2015-08-18
          • 2018-07-16
          • 2013-01-28
          • 2011-05-03
          • 1970-01-01
          • 2020-11-28
          相关资源
          最近更新 更多