考虑下面的代码,父类P没有无参构造函数,当调用子类C的有参构造函数时,由于没有采用C(int i):P(i)的形式,先调用父类的有参构造函数,所以P的无参构造函数会首先被调用!这样就会引起编译器报错。

 C++ |  copy code |? 
01
  class P{
02
      public:
03
          P(int i):val(i){}
04
 
05
      private:
06
          int val;
07
  };
08
 
09
  class C : public P{
10
      public:
11
          C(int i){
12
              P(i);
13
          }
14
  };
15
 
16
  int main(){
17
      C *c = new C(1);
18
      return 0;
19
  }

但是,如果子类C的有参构造函数,必须对它的参数先进行处理,然后才能初始化父类中的值,该怎么办呢?

答案是:为父类P添加一个无参构造函数,和一个接受参数的init函数。

 C++ |  copy code |? 
01
  class P{
02
      public:
03
          P(int i):val(i){}
04
          P(){}
05
 
06
          void init(int i){
07
              val = i;
08
          }
09
 
10
      private:
11
          int val;
12
  };
13
 
14
  class C : public P{
15
      public:
16
          C(int i){
17
              init(i);
18
          }
19
  };
20
 
21
  int main(){
22
      C *c = new C(1);
23
      return 0;
24
  }

那么结论是不是c++里子类想调用父类的构造函数,是不是只能在初始化列表里调用呢?这样不会太麻烦了吗?为什么这样设计呢?

另外,记得在某个地方看到过,如果一个类有可能成为别的类的父类,那么就必须要有无参构造函数。现在明白为什么了!

3 Comments

  1. Tenesha Messervy says:

    Following searching Google I found your site. I think both are great and I is going to be coming back again to you and them in the long term. Thanks

  2. Ted Harju says:

    Great information. Thanks a lot!

  3. Madie Laughridge says:

    I Too Like the Blog here. Keep up all the work. I too love to blog. This is great everyone sharing opinions

Leave a Reply