C++中派生类隐式调用与显式调用基类的构造函数
生活随笔
收集整理的這篇文章主要介紹了
C++中派生类隐式调用与显式调用基类的构造函数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
通過派生類的構(gòu)造函數(shù)調(diào)用基類的構(gòu)造函數(shù)有兩種方式,隱式和顯式兩種。
所謂隱式方式就是在派生類的構(gòu)造函數(shù)中不指定對應(yīng)的基類的構(gòu)造函數(shù),這個時候調(diào)用的是基類的默認(rèn)構(gòu)造函數(shù)(即含有默認(rèn)參數(shù)值或不帶參數(shù)的構(gòu)造函數(shù))。而所謂顯式方式,就是在派生類的構(gòu)造函數(shù)中指定要調(diào)用的基類的構(gòu)造函數(shù),并將派生類構(gòu)造函數(shù)的部分參數(shù)值傳遞給基類構(gòu)造函數(shù)。注:除非基類有默認(rèn)的構(gòu)造函數(shù),否則必須采用顯式調(diào)用方式
#include <iostream>
using namespace std;
class A
{
public:A(int x = 0,int y = 0){a = x;b = y;}
private:int a;int b;
};
//基類A有默認(rèn)的構(gòu)造函數(shù),可以隱式調(diào)用
class B:public A
{
public:B(int z = 0){c = z;}
private:int c;
};
int main()
{B b1;return 0;
}
#include <iostream>
using namespace std;
class A
{
public:A(int x,int y){a = x;b = y;}
private:int a;int b;
};
//基類A沒有默認(rèn)的構(gòu)造函數(shù),其現(xiàn)有的構(gòu)造函數(shù)需要傳遞參數(shù),通過
//派生類構(gòu)造函數(shù)調(diào)用A構(gòu)造函數(shù)時必須如下顯式調(diào)用
class B:public A
{
public:B(int x,int y,int z):A(x,y){c = z;}
private:int c;
};
int main()
{B b1(1,2,3);return 0;
}
?
總結(jié)
以上是生活随笔為你收集整理的C++中派生类隐式调用与显式调用基类的构造函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS2015无法打开包括文件corecr
- 下一篇: C++引用与指针的不同