C++编程 分析下列程序的输出结果

来源:百度知道 编辑:UC知道 时间:2024/06/27 08:08:31
#include<iostream>
using namespace std;
class A
{
public:
A();
A(int i,int j);
~A();
void Set(int i,int j){a=i,b=j;}
private:
int a,b;
};
A::A()
{
a=0;
b=0;
cout<<“Default constructor called.”<<endl;
}
A::A(int i,int j)
{
a=i;
b=j;
cout<<“Constructor:a=”<<a<<“,b=”<<b<<endl;
}
A::~A()
{
cout<<“Destructor called.a=”<<a<<“,b=”<<b<<endl;
}
int main()
{
cout<<“Starting1……”<<endl;
A a[3];
for(int i=0;i<3;i++)
a[i].Set(2*i+1,(i+1)*2);
cout<<“Ending1……”<<endl;
cout<<“string2……”<<endl;
A b[3]={A(1,2),A(3,4),A(5,6)};
cout<<“Ending2……”<<endl;
return 0;
}

分析越详细越好
输出结果是?

特别提醒几点:
1.在构造对象(定义对象)时要调用构造函数,调用哪个构造函数根据对象是否赋初始值而定,“要对应的”.

2.对象的生命期结束时要调用析构函数,析构的顺序和构造的顺序相反!!!!

结果是:
Starting1......
Default constructor called.
Default constructor called.
Default constructor called.
Ending1......
Starting2......
Constructor:a=1,b=2
Constructor:a=3,b=4
Constructor:a=5,b=6
Ending2......
Destructor called.a=5,b=6
Destructor called.a=3,b=4
Destructor called.a=1,b=2
Destructor called.a=5,b=6
Destructor called.a=3,b=4
Destructor called.a=1,b=2

和main函数对应的分析如下:
int main()
{
cout<<“Starting1……”<<endl;
A a[3];
for(int i=0;i<3;i++)
a[i].Set(2*i+1,(i+1)*2);
cout<<“Ending1……”<<endl;
cout<<“string2……”<<endl;
A b[3]={A(1,2),A(3,4),A(5,6)};
cout<<“Ending2……”<<endl;
return 0;
}

【1】.执行cout<<“Starting1……”<