马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
下面的代码理论上有四个对象,为什么却析构了3次,为什么??#include <iostream>
using namespace std;
class Location
{
public:
Location(int a, int b)
{
x = a, y = b;
cout<<"Executing constructor"<<endl;
cout<<"x = "<<x<<", y = "<<y<<endl;
}
Location(const Location& p)
{
x = p.x; y = p.y;
cout<<"Executing copy_constructor."<<endl;
cout<<"x = "<<x<<", y = "<<y<<endl;
}
~Location()
{
cout<<"Executing destructor"<<endl;
}
double getx()
{
return x;
}
double gety()
{
return y;
}
private:
int x, y;
};
Location fun(Location p)
{
int x, y;
x = p.getx() + 1;
y = p.gety() + 1;
cout<<"x = "<<x<<", y = "<<y<<endl;
return p;
}
void main()
{
Location p1(5, 18);
Location p2 = fun(p1);
}
如果把最后一条代码改为:Location p2 = p1,那么p1赋值p2调用了复制构造函数,为什么多了fun(p1)就不析构了fun(p1)赋值给p2,其中fun函数就有调用了两个复制构造函数!!!#include <iostream>
using namespace std;
class Location
{
public:
Location(int a, int b)
{
x = a, y = b;
cout<<"Executing constructor"<<endl;
cout<<"x = "<<x<<", y = "<<y<<endl;
}
Location(const Location& p)
{
x = p.x; y = p.y;
cout<<"Executing copy_constructor."<<endl;
cout<<"x = "<<x<<", y = "<<y<<endl;
}
~Location()
{
cout<<"Executing destructor"<<endl;
}
double getx()
{
return x;
}
double gety()
{
return y;
}
private:
int x, y;
};
Location fun(Location p)
{
int x, y;
x = p.getx() + 1;
y = p.gety() + 1;
cout<<"x = "<<x<<", y = "<<y<<endl;
return p;
}
void main()
{
Location p1(5, 18);
Location p2 = p1;
}
|