构造函数与派生类构造函数

构造函数与派生类构造函数


 

相关链接: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         }

 

 那么,派生类构造函数对基类构造函数进行初始化的操作,您看懂了吗?

文章如有不足之处,请指出,一定加以改正,谢谢

转载于:https://www.cnblogs.com/whtmomo/p/11338420.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值