形式の多様な構造関数
1、コピー構築関数:
モデル:
コピーコンストラクション関数が呼び出されるのは、(1)クラスの1つのオブジェクトでクラスの別のオブジェクトを初期化するときです.システムは自動的にそれを呼び出してコピーの割り当てを実現します:A a(1,1);A b(a); (2)関数のパラメータがクラスのオブジェクトである場合、関数を呼び出すと、実パラメータにパラメータが付与され、システムは自動的にコピー関数を呼び出す. test(A a); A aa; test(aa);
2、組合せクラス構築関数
モデル:クラス::クラス(オブジェクトメンバーに必要なパラメータ、このクラスメンバーパラメータ):オブジェクト1(パラメータ)、オブジェクト2(パラメータ)……{このクラス初期化}呼び出し順序:埋め込みオブジェクトのコンストラクション関数を先に呼び出し、先に宣言した先呼び出し.デフォルトコンストラクション関数の場合、埋め込みオブジェクトの初期化も対応するデフォルトコンストラクション関数を呼び出し、コンストラクションが逆になります.例:
結果:
base create
test create
test destroy
base destroy
例:コピーコンストラクション関数と組合せクラスコンストラクション関数の混用
結果:
base create
copy create
copy create
test create
base destroy
test destroy
base destroy
3、継承関係を含む構造関数
モデル:派生クラス:派生クラス(ベースクラス1新パラメータ、ベースクラス2新パラメータ、ベースクラス3形パラメータ、...、ベースクラスn新パラメータ、本クラス新パラメータ):ベースクラス1(パラメータ)、ベースクラス2(パラメータ)、ベースクラスn(パラメータ)、オブジェクトデータメンバー初期化{本クラスメンバー初期化付与文;
};
例:
C(int a,int b,int c,int d): B1(a),memberB2(d),memberB1(c),B2(b) { }
例を挙げないで、多すぎます.
モデル:
class A
{
public :
A(A& a){
//
}
};
コピーコンストラクション関数が呼び出されるのは、(1)クラスの1つのオブジェクトでクラスの別のオブジェクトを初期化するときです.システムは自動的にそれを呼び出してコピーの割り当てを実現します:A a(1,1);A b(a); (2)関数のパラメータがクラスのオブジェクトである場合、関数を呼び出すと、実パラメータにパラメータが付与され、システムは自動的にコピー関数を呼び出す. test(A a); A aa; test(aa);
2、組合せクラス構築関数
モデル:クラス::クラス(オブジェクトメンバーに必要なパラメータ、このクラスメンバーパラメータ):オブジェクト1(パラメータ)、オブジェクト2(パラメータ)……{このクラス初期化}呼び出し順序:埋め込みオブジェクトのコンストラクション関数を先に呼び出し、先に宣言した先呼び出し.デフォルトコンストラクション関数の場合、埋め込みオブジェクトの初期化も対応するデフォルトコンストラクション関数を呼び出し、コンストラクションが逆になります.例:
class Base
{
private:
int b1;
int b2;
public:
Base(int b1,int b2)
{
printf("base create
");
this->b1 = b1;
this->b2 = b2;
}
~Base()
{
printf("base destroy
");
}
};
class Test
{
private:
int t1;
Base b;
public:
Test(int b1,int b2,int t1):b(b1,b2)
{
printf("test create
");
this->t1 = t1;
}
~Test()
{
printf("test destroy
");
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Test* test = new Test(1,2,3);
delete test;
int in;
scanf("&d",in);
}
結果:
base create
test create
test destroy
base destroy
例:コピーコンストラクション関数と組合せクラスコンストラクション関数の混用
#include "stdafx.h"
#include <iostream>
using namespace std;
class Base
{
private:
int b1;
int b2;
public:
Base(int b1,int b2)
{
printf("base create
");
this->b1 = b1;
this->b2 = b2;
}
Base(Base & b)
{
printf("copy create
");
}
~Base()
{
printf("base destroy
");
}
};
class Test
{
private:
int t1;
Base b;
public:
Test(Base b1,int t1):b(b1)
{
printf("test create
");
this->t1 = t1;
}
~Test()
{
printf("test destroy
");
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base b(1,2);
Test* test = new Test(b,3);
delete test;
int in;
scanf("&d",in);
}
結果:
base create
copy create
copy create
test create
base destroy
test destroy
base destroy
3、継承関係を含む構造関数
モデル:派生クラス:派生クラス(ベースクラス1新パラメータ、ベースクラス2新パラメータ、ベースクラス3形パラメータ、...、ベースクラスn新パラメータ、本クラス新パラメータ):ベースクラス1(パラメータ)、ベースクラス2(パラメータ)、ベースクラスn(パラメータ)、オブジェクトデータメンバー初期化{本クラスメンバー初期化付与文;
};
例:
C(int a,int b,int c,int d): B1(a),memberB2(d),memberB1(c),B2(b) { }
例を挙げないで、多すぎます.