C++ defaul construct :缺省构造函数(默认构造函数)

定义:第一种   构造函数没有参数,即是 A()形式的

       第二种   构造函数的全部参数由缺省值提供,A(int a=0,int b=0)

 

编译器添加的默认构造函数的条件:   如果创建一个类你没有写任何构造函数,则系统会自动生成默认的无参构造函数,函数为空,什么都不做(这只是一种情况而言,此构造函数是trival

 

 

派生类和基类的关系:

我们通常说的派生类和基类,我们调用派生类的自定义的构造函数的时候,派生类会自动调用基类中的default construct函数,而不能调用基类中的其他构造函数

class Foo 
{ 
  private: 
  int val; 
public:
    Foo():val(9){}
}; 
class Bar:public Foo 
{ 
public: 
  char *str; 
  int i; 
  Bar(int i,char*s){
      i=i;
      str=s;
  }
}; 


//不能通过,因为bar派生类不能调用基类中的defalut函数,因为不存在
class Foo 
{ 
  private: 
  int val; 
  Foo(int i):val(i){}
}; 
class Bar:public Foo 
{ 
public: 
  char *str; 
  int i; 
  Bar(int i,char*s){
      i=i;
      str=s;
  }
}; 
 
class Foo 
{ 
  private: 
  int val; 
public:
  Foo(int i):val(i){}
  Foo():val(6){}
}; 
class Bar:public Foo 
{ 
public: 
  char *str; 
  int i; 
  Bar(int i,char*s){
      i=i;
      str=s;
  }
}; 
base中同时定义普通构造函数和default construct函数的时候,派生类就可以调用

 

相关文章:

  • 2021-08-21
  • 2022-12-23
  • 2022-12-23
  • 2022-01-14
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-11
  • 2021-12-06
  • 2022-01-04
  • 2022-12-23
  • 2021-09-10
相关资源
相似解决方案