c++复制构造函数(浅拷贝、深拷贝)

#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
    A(int i, int j){ n = i; m = j; }
    A(A &t){ n = t.n; m = t.m; }//默认的复制构造函数,即使把这一行注释掉仍能正确执行
    void print(){ cout << n << m << endl; }
private:
    int n;
    int m;

};

int main()
{
    A a(2, 4);
    a.print();
    A b(a);
    b.print();
    system("pause");
    return 0;
}
#include<iostream>
#include<stdlib.h>
using namespace std;
class A
{
public:
    A(){ x = new int; *x = 5; }
    ~A(){ delete x; x = NULL; }
    //A(const A&a){ cout << "复制构造函数执行" << endl; x = a.x; }//即使我们不写这样一个复制构造函数,系统也会默认存在这样一个复制构造函数。浅拷贝
    A(const A&a){ cout << "复制构造函数执行" << endl; x = new int; *x = *(a.x); }//深拷贝
    void print()const{ cout << *x; }
    void set(int i){ *x = i; }
private:
    int *x;
};

int main()
{
    A *a = new A;
    cout << "a:"; a->print();cout << endl;
    A b = *a;
    a->set(32);
    cout << "b:"; b.print(); cout << endl;
    b.set(99);
    cout << "a:"; a->print(); cout << endl;
    system("pause");
    return 0;
}

默认构造函数的复制方式,叫做成员拷贝,又叫浅拷贝,这种浅拷贝方式易出现迷途指针。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值