#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;
}
運行結果為什么是:
Constructor1
Constructor1
Constructor1
Constructor1
Destructor
Constructor2
Destructor
Constructor3
Destructor
x=0,y=0
x=5,y=0
x=2,y=3
Destructor
Destructor
Destructor
它是如何調用構造函數和析構函數的???思考以下我想可能是這樣運行的:B *ptr ; //建立一個指針對象 先調用一次構造函數B();ptr=new B[3]; //用new獲取動態內存,并且建立了3個對象ptr[0]=B(); //調用構造函數B() ptr[1]=B(5); //調用重載構造函數B(int i)ptr[2]=B(2,3) //調用重載構造函數B(int i,intj)然后調用一次析構函數;最后 delete[] ptr; 逆序調用三次析構函數.
posted on 2011-06-01 13:38
DoubleW 閱讀(3267)
評論(2) 編輯 收藏 引用