デフォルトのコンストラクターの構築操作
デフォルトのコンストラクターを持つ1つのメンバーオブジェクト
1.1動作
外部オブジェクトにメンバーオブジェクトが含まれている場合、メンバーオブジェクトコンストラクターが明示的に呼び出されていない場合、コンパイラーは自動的に呼び出しを追加します。
1.2サンプルコード
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {
cout << "call A()" << endl; }
A(int value) {
cout << "call A(value)" << endl; }
};
class B
{
private:
A a;
int value;
string name;
public:
B() {
name = "aloha";
}
void show()
{
cout << "B value=" << value << ",name=" << name <<endl;
};
};
int main()
{
B b;
b.show();
}
1.3出力
call A()
B value=-858993460,name=aloha
注:
コメントコードにAのデフォルトのコンストラクターがある場合、コンパイルはパスしません。
デフォルト以外のAのコンストラクターは、初期化リストを介してBのコンストラクターで明示的に呼び出す必要があります。
B():a(0) {
name = "aloha";
}
2親タイプにはデフォルトのコンストラクターがあります
2.1動作
サブタイプのコンストラクターでは、親タイプのコンストラクターが自動的に呼び出されます。
2.2サンプルコード1
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {
cout << "call A()" << endl; }
A(int value) {
cout << "call A(value)" << endl; }
};
class AA:public A
{
int value;
string name;
public:
AA() {
value = 0;
name = "aloha";
}
void show()
{
cout << "AA value=" << value << ",name=" << name << endl;
};
};
int main()
{
AA aa;
aa.show();
}
2.3出力1
call A()
AA value=0,name=aloha
2.4サンプルコード2
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {
cout << "call A()" << endl; }
A(int value) {
cout << "call A(value)" << endl; }
};
class AA:public A
{
int value;
string name;
public:
AA()
{
value = 0;
name = "aloha";
}
AA(int value)
{
this->value = value;
name = "aloha";
}
void show()
{
cout << "AA value=" << value << ",name=" << name << endl;
};
};
int main()
{
AA aa(5);
aa.show();
}
2.5出力2
call A()
AA value=5,name=aloha
3両方の場合
3.1動作
最初に親クラスのデフォルトの構築メソッドを呼び出し、次にメンバーオブジェクトのデフォルトの構築メソッドを呼び出します
3.2サンプルコード
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A() {
cout << "call A()" << endl; }
A(int value) {
cout << "call A(value)" << endl; }
};
class B
{
public:
B() {
cout << "call B()" << endl; }
B(int value) {
cout << "call B(value)" << endl; }
};
class AAB:public A
{
int value;
string name;
B b;
public:
AAB()
{
value = 0;
name = "aloha";
}
AAB(int value)
{
cout << "AAB start" << endl;
this->value = value;
name = "aloha";
cout << "AAB end" << endl;
}
void show()
{
cout << "AAB value=" << value << ",name=" << name << endl;
};
};
int main()
{
AAB aab(5);
aab.show();
}
3.3出力
call A()
call B()
AAB start
AAB end
AAB value=5,name=aloha
4つの参照
「C ++オブジェクトモデルの詳細な調査」、Stanley B.Lippman著、Hou Jie訳、Electronic Industry Press、2012年。