看下这个程序
#include<iostream>using namespace std;
class test
{
public:
test();
test(int i,int j);
~test()
{
cout<<"Destructor called:"<<X<<','<<Y<<endl;
}
void set(int i,int j);
void print()
{
cout<<X<<","<<Y<<endl;
}
private:
int X,Y;
};
test::test()
{
X=Y=0;
cout<<"Default constructor 2332312called"<<endl;
}
test::test(int i,int j)
{
X=i;
Y=j;
cout<<"Constructorcalled:"<<X<<','<<Y<<endl;
}
void test::set(int i,int j)
{
X=i;
Y=j;
}
int main()
{
test*ptr1,*ptr2,*ptr3;
ptr1=new test(1,2);
ptr2=new test(3,4);
ptr3=new test[2];
ptr3[0].set(5,6);
ptr3[1].set(7,8);
ptr1->print();
ptr2->print();
ptr3[0].print();
ptr3[1].print();
delete ptr1;
delete ptr2;
delete []ptr3;
cin.get();
cin.get();
return 0;
}
在这个程序里运行结果是
Constructorcalled:1,2
Constructorcalled:3,4
Default constructor 2332312called
Default constructor 2332312called
1,2
3,4
5,6
7,8
Destructor called:1,2
Destructor called:3,4
Destructor called:7,8
Destructor called:5,6
为什么第三行会出现两次啊,我怎么觉得应该出现一次呢