1. 程式人生 > >C++中子類呼叫父類的有參建構函式

C++中子類呼叫父類的有參建構函式

 轉自:https://blog.csdn.net/sddyljsx/article/details/9156055

參考:

https://blog.csdn.net/qq_36846891/article/details/69666437 //java中子類構造與父類構造

https://blog.csdn.net/dan_lionly/article/details/52314869 //c++中子類構造與父類構造

#include <iostream>
using namespace std;
class A
{
public:
int a;
int b;
A()
{
cout<<"A Constructed\n";
}
};
class B:A
{
public:
int c;
int d;

B()
{
cout<<"B Constructed\n";
}

};

int main()
{

B b;
return 1;

}

如上面程式碼所示,B類繼承自A類,當生成B的例項b時,要先執行A的建構函式,然後執行B的建構函式。結果如下所示:

若B使用有參建構函式,如下面程式碼所示,仍然會呼叫A的無參建構函式。

#include <iostream>

using namespace std;

class A
{
public:
int a;
int b;

A()
{
cout<<"A Constructed 1\n";
}
A(int a,int b)
{
this->a=a;
this->b=b;
cout<<"A Constructed 2\n";
}

};

class B:A
{
public:
int c;
int d;

B()
{
cout<<"B Constructed 1\n";
}

B(int c,int d)
{
this->c=c;
this->d=d;
cout<<"B Constructed 2\n";
}

};

int main()
{
B b(1,1);
return 1;
}

執行結果:

但是如何在建構函式中呼叫父類的有參建構函式呢?實現程式碼如下:​​​​​​​

#include <iostream>
using namespace std;

class A
{
public:
int a;
int b;
A()

{
cout<<"A Constructed 1\n";
}

A(int a,int b)
{
this->a=a;
this->b=b;
cout<<"A Constructed 2\n";
}

};

class B:A
{

public:
int c;
int d;

B()
{
cout<<"B Constructed 1\n";
}

B(int c,int d):A(100,200)
{
this->c=c;
this->d=d;
cout<<"B Constructed 2\n";
}
};

int main()
{
B b(1,1);
return 1;
}

執行結果: