C++复制控制成员

理解复制控制成员和构造函数的一个良好方式是定义一个简单的类,该类具有这些成员,每个成员打印自己的名字

#include <iostream>
#include <vector>
using namespace std;
struct Expl {
    Expl(){cout << "Expl()" << endl;}
    
    Expl(const Expl &) {cout << "Expl(const Expl&)" << endl;}
    
    Expl& operator=(const Expl&)
    {
        cout << "Expl& operator=(const Expl&)" << endl;
        return *this;
    }
    
    ~Expl(){cout << "~Expl()" << endl;}
};

void fun1(Expl expl)
{
}

void fun2(Expl &)
{
    
}

Expl fun3() 
{
    Expl obj;
    return obj;
}

int main (int argc, const char * argv[])
{

    // insert code here...
    Expl expl;
    fun1(expl);
    fun2(expl);
    
    expl = fun3();
    Expl *p = new Expl;
    vector<Expl> evect(3);
    
    delete  p;
    return 0;
}

编写一个像Expl这样的类,给出复制控制成员和其他构造函数。然后写一个程序,用不同方式使用Expl类型的对象:作为非引用形参和引用形参传递,动态分配,放在容器中,等等。研究何时执行哪个构造函数和复制控制成员,可以帮助你融会贯通地理解这些概念。


下面的输出结果,仅供参考,因为不同版本C++编译结果可能不同

Expl()

Expl(const Expl&)

~Expl()

Expl()

Expl& operator=(const Expl&)

~Expl()

Expl()

Expl()

Expl(const Expl&)

Expl(const Expl&)

Expl(const Expl&)

~Expl()

~Expl()

~Expl()

~Expl()

~Expl()

~Expl()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值