#include<iostream>usingnamespace std;classA{int h,i,j;staticint k;//必須在類體外初始化};classB:A{int m,n,p;conststaticint q =0;//const 只能在體外或者體內一處有值};int A::k =0;//靜態數據成員必須初始化intmain(){
cout <<"size of int : "<<sizeof(int)<< endl;
cout <<"size of A :"<<sizeof(A)<< endl;
cout <<" size of B :"<<sizeof(B)<< endl;system("pause");return0;}
運行結果
size of int:4
size of A :12
size of B :24
示例代碼
classBAG{int*const e;constint s;int p;public:BAG(int m):e(newint[m]),s(e ? m :0){ p =0;}~BAG(){if(e){delete e;*(int*)&s =0;*(int**)&e =0;//0代表空指針}}intgetp(){return p;}inthave(int f){for(int i =0; i < p; i++){if(e[i]== f)return1;return0;}}};classSET:protected BAG{//不允許重複的元素,故須覆蓋基類的putepublic:
BAG::getp;
BAG::have;//從保護恢復爲publicintpute(int f){returnhave(f)?1:BAG::have(f);//不能去掉BAG::,遞歸}SET(int m):BAG(m){}//C++缺省的析構函數~SET( )自動調用~BAG( )};//若定義析構函數,形式爲~SET( ){ },功能同缺省析構函數