(原創) derived-class要怎麼呼叫base-class的constructor? (C/C++)

本文介绍在C++中如何从派生类构造函数调用基类构造函数,通过实例演示如何传递参数到基类构造函数,适用于抽象基类场景。展示了具体的代码实现,包括初始化列表的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有時我們在derived-class的constructor提供的參數,事實上是base-class的資料,或者base-class根本就是ABC(abstract base class),這時我們就得在derived-class的constructor去呼叫base-class的constructor。

 1 ExpandedBlockStart.gif ContractedBlock.gif /**/ /* 
 2InBlock.gif(C) OOMusou 2007 http://oomusou.cnblogs.com
 3InBlock.gif
 4InBlock.gifFilename    : Constructor_CallBaseConstructor.cpp
 5InBlock.gifCompiler    : Visual C++ 8.0 / gcc 3.4.2 / ISO C++
 6InBlock.gifDescription : Demo how to call base class constructor
 7InBlock.gifRelease     : 02/16/2007 1.0
 8ExpandedBlockEnd.gif*/

 9 None.gif#include  < iostream >
10 None.gif#include  < string >
11 None.gif
12 None.gif using   namespace  std;
13 None.gif
14 ExpandedBlockStart.gifContractedBlock.gif class  Student  dot.gif {
15InBlock.gifpublic:
16InBlock.gif  string name;
17InBlock.gifpublic:
18ExpandedSubBlockStart.gifContractedSubBlock.gif  Student() dot.gif{}
19InBlock.gif  
20ExpandedSubBlockStart.gifContractedSubBlock.gif  Student(const char *name) dot.gif{
21InBlock.gif    this->name = string(name);
22ExpandedSubBlockEnd.gif  }

23ExpandedBlockEnd.gif}
;
24 None.gif
25 ExpandedBlockStart.gifContractedBlock.gif class  Bachelor :  public  Student  dot.gif {
26InBlock.gifpublic:
27InBlock.gif  string lab;
28InBlock.gif  
29InBlock.gifpublic:
30ExpandedSubBlockStart.gifContractedSubBlock.gif  Bachelor() dot.gif{}
31InBlock.gif 
32ExpandedSubBlockStart.gifContractedSubBlock.gif  Bachelor(const char *name, const char *lab) : Student(name) dot.gif{
33InBlock.gif    this->lab = string(lab);
34ExpandedSubBlockEnd.gif  }

35ExpandedBlockEnd.gif}

36 None.gif
37 ExpandedBlockStart.gifContractedBlock.gif int  main()  dot.gif {
38InBlock.gif  Bachelor bachelor("John","PECLab");
39InBlock.gif  cout << bachelor.name << endl;
40InBlock.gif  cout << bachelor.lab << endl;
41ExpandedBlockEnd.gif}


執行結果

None.gif John
None.gifPECLab


32行的constructor提供了兩個參數,name為base-class的資料,而lab為derived-class的資料,所以勢必呼叫base-class的constructor才行,C++的方式是在constructor initializer list中呼叫base-class的constructor名稱,並帶入參數,這樣就可以執行base-class的constructor了。

C#是在constructor initializer list使用base這個keyword,而Java是在body中使用super這個keyword。

See Also
(原創) derived-class要怎麼呼叫base-class的constructor? (.NET) (C#)
(原創) derived-class要怎麼呼叫base-class的constructor? (Java)

Reference
C++ Primer 4th section 15.4.2 p.582

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值