// 调用拷贝构造函数的三种情况
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(int len=10, int wid=10);
Rectangle(const Rectangle &p);
~Rectangle() { cout<<"Using 析构 constructor"<<endl;};
void disp()
{ cout<<length<<" "<<width<<endl; }
private:
int length, width;
};
Rectangle::Rectangle(int len, int wid)
{
length = len;
width = wid;
cout<<"Using normal constructor\n";
}
// 调用①
Rectangle::Rectangle(const Rectangle &p)
{
length = 2*p.length;
width = 2*p.width;
cout<<"Using copy constructor\n";
}
// 调用② 对象作函数参数
void fun1(Rectangle p)
{ p.disp();
}
// 调用③ 函数返回值为对象
Rectangle fun2()
{ Rectangle p4(10,30);
return p4;}
int main()
{
Rectangle p1(30,40);
p1.disp();
Rectangle p2(p1);
p2.disp();
Rectangle p3=p1;
p3.disp();
fun1(p1);
p2=fun2();
p2.disp();
return 0;
}
运行结果:
Using normal constructor
30 40
Using copy constructo
60 80
Using copy constructo
60 80
Using copy constructo
60 80
Using XiGou constructor.
Using normal constructor
Using XiGou constructor.
10 30
Using XiGou constructor.
Using XiGou constructor.
Using XiGou constructor.
--------------------------------
Process exited after 0.1117 seconds with return value 0
请按任意键继续. . .
Conclusion:
①当类对象作为函数参数,调用函数时,在形参中的对象会调用拷贝构造函数
②当类对象作为函数类型时,main函数中调用该函数的对象不会执行拷贝构造函数