#include <iostream.h>
class B
{
int x,y;
public:
B() {x = y = 0; cout << “Constructor1” << endl;}
B(int i) {x = i; y = 0; cout << “Constructor2” << endl;}
B(int i ,int j) {x = i; y = j; cout << “Constructor3” << endl;}
~B() {cout << “Destructor” << endl;}
void print() {cout << “x=” << x << “,y=” << y << endl;}
};
void main()
{
B *ptr;
ptr = new B[3];
ptr[0] = B();
ptr[1] = B(5);
ptr[2] = B(2,3);
for (int i=0;i<3;i++)
ptr[i].print();
delete[] ptr;
}
運(yùn)行結(jié)果為什么是:
Constructor1
Constructor1
Constructor1
Constructor1
Destructor
Constructor2
Destructor
Constructor3
Destructor
x=0,y=0
x=5,y=0
x=2,y=3
Destructor
Destructor
Destructor
它是如何調(diào)用構(gòu)造函數(shù)和析構(gòu)函數(shù)的???思考以下我想可能是這樣運(yùn)行的:B *ptr ; //建立一個(gè)指針對(duì)象 先調(diào)用一次構(gòu)造函數(shù)B();ptr=new B[3]; //用new獲取動(dòng)態(tài)內(nèi)存,并且建立了3個(gè)對(duì)象ptr[0]=B(); //調(diào)用構(gòu)造函數(shù)B() ptr[1]=B(5); //調(diào)用重載構(gòu)造函數(shù)B(int i)ptr[2]=B(2,3) //調(diào)用重載構(gòu)造函數(shù)B(int i,intj)然后調(diào)用一次析構(gòu)函數(shù);最后 delete[] ptr; 逆序調(diào)用三次析構(gòu)函數(shù).
posted on 2011-06-01 13:38
DoubleW 閱讀(3267)
評(píng)論(2) 編輯 收藏 引用