生活随笔
收集整理的這篇文章主要介紹了
C++中的虚继承
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
如果一個(gè)派生類從多個(gè)基類派生,而這些基類又有一個(gè)共同的基類,則在對該基類中聲明
的名字進(jìn)行訪問時(shí),可能產(chǎn)生二義性
如果一個(gè)派生類從多個(gè)基類派生,而這些基類又有一個(gè)共同
的基類,則在對該基類中聲明的名字進(jìn)行訪問時(shí),可能產(chǎn)生
二義性
如果在多條繼承路徑上有一個(gè)公共的基類,那么在繼承路徑的某處
匯合點(diǎn),這個(gè)公共基類就會(huì)在派生類的對象中產(chǎn)生多個(gè)基類子對象
#include <iostream>
using namespace std
;class B
{
private
:
public
:int b
;B();~B();
};B
::B()
{cout
<< "sonstruct B" << endl
;
}B
::~B()
{
}class B1
: public B
{
public
:int b1
;};class B2
: public B
{
public
:int b2
;
};class C
: public B1
, public B2
{
public
:int c
;
};int main(int argc
, char *argv
[])
{C c1
;c1
.b1
= 100;c1
.b2
= 200;c1
.c
= 300;c1
.B1
::b
= 500; c1
.B2
::b
= 500;cout
<<"hello..."<<endl
;return 0;
}
? 要使這個(gè)公共基類在派生類中只產(chǎn)生一個(gè)子對象,必須對這個(gè)基類
聲明為虛繼承,使這個(gè)基類成為虛基類。
? 虛繼承聲明使用關(guān)鍵字 virtual
增加 virtual關(guān)鍵字之后,基類構(gòu)造函數(shù)其實(shí)只調(diào)用了一次
#include <iostream>
using namespace std
;class B
{
private
:
public
:int b
;B();~B();
};B
::B()
{cout
<< "sonstruct B" << endl
;
}B
::~B()
{
}class B1
: virtual public B
{
public
:int b1
;};class B2
: virtual public B
{
public
:int b2
;
};class C
: public B1
, public B2
{
public
:int c
;
};int main(int argc
, char *argv
[])
{C c1
;c1
.b1
= 100;c1
.b2
= 200;c1
.c
= 300;c1
.b
= 500; c1
.B1
::b
= 500;c1
.B2
::b
= 500;cout
<<"hello..."<<endl
;return 0;
}
執(zhí)行結(jié)果如下:
construct B
hello
...
總結(jié)
以上是生活随笔為你收集整理的C++中的虚继承的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。