C++ 学习之路(1):拷贝构造函数

// 调用拷贝构造函数的三种情况
#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函数中调用该函数的对象不会执行拷贝构造函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值