C++サブクラス解析問題
2973 ワード
**************base.h*****************
class base
#ifndef __base_h
#define __base_h
class base
{
public:
base(int a,int b);
~base();
public:
int m;
int n;
};
#endif
**************base.cpp***************
#include "stdafx.h"
#include "base.h"
base::base(int a, int b)
{
m=a;
n=b;
printf("gou zao ji lei
");
}
base::~base()
{
printf("xi gou ji lei
");
}
**************frombase.h************
サブクラスfrombaseの作成ベースクラスclass baseの継承
#ifndef __use_h
#define __use_h
#include "base.h"
class frombase:public base
{
public:
frombase(int q,int w,int e,int r);
~frombase();
public:
int x;
int y;
};
#endif
************frombase.cpp************
#include "stdafx.h"
#include "use.h"
frombase::frombase(int q,int w,int e,int r):base(e,r)
{
x=q;
y=w;
}
frombase::~frombase()
{
printf("xi gou frombase
");
}
C++コンソールプログラムテスト11
#include "stdafx.h"
#include "base.h"
#include "use.h"
//int _tmain(int argc, _TCHAR* argv[])
int main()
{
int aa =1;
int bb =2;
int cc = 3;
int dd = 4;
base* _base;
frombase * _frombase;
_base = (base*)new frombase(aa,bb,cc,dd);
printf("%d %d
",_base->m,_base->n);
delete _base;
getchar();
return 0;
}
::
ベースクラスbaseの構築
サブクラスfrombaseの構築
3 4
プロファイルベースクラスbase
C++コンソールプログラムテスト22
#include "stdafx.h"
#include "base.h"
#include "use.h"
int main()
{
int aa =1;
int bb =2;
int cc = 3;
int dd = 4;
base* _base;
frombase * _frombase;
_base = (base*)new frombase(aa,bb,cc,dd);
printf("%d %d
",_base->m,_base->n);
_frombase = (frombase*)_base;
printf("%d %d %d %d
",_frombase->m,_frombase->n,_frombase->x,_frombase->y);
delete _frombase;
getchar();
return 0;
}
:::
ベースクラスbaseの構築
サブクラスfrombaseの構築
3 4
3 4 1 2
プロファイルサブクラスfrombaseプロファイルベースクラスbase
まとめ:サブクラスのオブジェクトが直接解放された場合:
サブクラス自体の構造関数を呼び出してからベースクラスの構造関数を呼び出す
サブクラスのオブジェクトがベースクラスタイプに強制的に変換された場合:
ベースクラスの構造関数を直接呼び出し、サブクラスの構造関数を無視します.