关于c++对象数组初始化时产生的临时变量析构问题？

``````#include <iostream>
using namespace std;
class Point
{ public:
Point():x(0),y(0)
{   cout<<"Default Constructor called.\n";}
Point(int xx,int yy):x(xx),y(yy)
{   cout<< "Constructor called.\n";  }
~Point()
{   cout<<"Destructor called.\n";    }
void Move(int xx,int yy)    {  x=xx;  y=yy;   }
private:
int  x,y;
};
int main()
{
Point A[2]={Point(1,2),Point()};
cout<<"hello"<<endl;
return 0;
}``````

``````#include <iostream>
using namespace std;
class B
{
int x, y;
public:
B();
B(int i);
B(int i, int j);
~B();
void Print();
};
B::B() :x(0), y(0)
{
cout << "Default constructor called.\n";
}
B::B(int i) : x(i), y(0)
{
cout << "Constructor 1 called.\n";
}
B::B(int i, int j) : x(i), y(j)
{
cout << "Constructor 2 called.\n";
}
B::~B()
{
cout << "Destructor called.\n";
}
void B::Print()
{
cout << "x=" << x << ", y=" << y << endl;
}
int  main()
{
B *p;
p = new B[3];
cout << "*******" << endl;
p[0] = B();
p[1] = B(7);
p[2] = B(5, 9);
for (int i = 0; i < 3; i++)
p[i].Print();
cout << "*******" << endl;
delete[]p;
}

``````

3 个回答
• 17

——————————

——————————

• 258

1.栈空间申请变量的生存期，在超出作用范围时销毁，这个作用范围在main函数。
2.delete的不用多说。首先B[3]也是栈空间，但是你重新赋值后他的，使命就结束了，尽早回收。

``Point A[2]={Point(1,2),Point()};``

``````p = new B[3];
cout << "*******" << endl;
p[0] = B();
p[1] = B(7);
p[2] = B(5, 9);``````