构造函数与派生类构造函数
相关链接:https://www.runoob.com/cplusplus/cpp-constructor-destructor.html
构造函数
首先我们需要知道,到底什么叫做构造函数?它的作用是什么呢?
构造函数是类中一种特殊的函数,它不具备返回值,并且函数名称必须与类名一致,当类创建对象的时候自动调用。
需要强调的是,当你创建一个类,系统会自动为你生成隐式的无参构造函数和析构函数。
构造函数一般用作初始化数据成员
构造函数与其他函数的特性具有共同之处,显著的相同点是它可以重载,接下来,用代码来简单演示一下。
1 #include <iostream> 2 using namespace std; 3 class Time{ 4 private: 5 int h; 6 int m; 7 int s; 8 public: 9 Time(){ 10 h = 0; 11 m = 0; 12 s = 0; 13 } 14 Time(int h,int m,int s){ 15 this->h = h; 16 this->m = m; 17 this->s = s; 18 } 19 /* 效果同上,初始化方式的多样化 20 Time(int h,int m,int s):h(h),m(m),s(s){} 21 */ 22 void display(){ 23 cout<<h<<":"<<m<<":"<<s<<endl; 24 } 25 26 } 27 int main(){ 28 Time t(10,29,25); //调用有参构造函数 29 t.display(); 30 return 0; 31 }
注意调用方式以及构造函数初始化的多样化。
派生类构造函数初始化
派生类继承来自基类,除了自己的成员,还包括基类的成员,当基类和派生类具有同样个数的含参构造函数,创建对象时,它的值是赋给的基类还是派生类就出现了歧义,一下举个例子:
1 #include <iostream> 2 using namespace std; 3 class Time{ 4 private: 5 int h; 6 int m; 7 int s; 8 public: 9 Time(){ 10 h = 0; 11 m = 0; 12 s = 0; 13 } 14 Time(int h,int m,int s){ 15 this->h = h; 16 this->m = m; 17 this->s = s; 18 } 19 /* 效果同上,初始化方式的多样化 20 Time(int h,int m,int s):h(h),m(m),s(s){} 21 */ 22 23 24 25 26 } 27 class Date{ 28 private: 29 int year; 30 int month; 31 int day; 32 public: 33 Date(){ 34 year = 0; 35 month = 0; 36 day = 0; 37 } 38 Date(int year,int month,int day){ 39 this->year = year; 40 this->month = month; 41 this->day = day; 42 } 43 void display(){ 44 cout<<year<<" "<<month<<<<" "<<day<<endl;
cout<<h<<":"<<m<<":"<<s<<endl; 45 } 46 } 47 int main(){ 48 Date d(1998,11,20); //调用有参构造函数,但是,这三个参数到底是给基类还是派生类呢? 49 d.display(); 50 return 0; 51 }
这是一个歧义的问题,那么该如何解决呢?
想要通过派生类的构造函数对基类构造函数进行初始化,需要这样操作,如下:
1 Date(int year,int month,int day,int h,int m,int s):Time(h,m,s){ 2 this->year = year; 3 this->month = month; 4 this->day = day; 5 }
那么,派生类构造函数对基类构造函数进行初始化的操作,您看懂了吗?
文章如有不足之处,请指出,一定加以改正,谢谢