C++中的深浅拷贝与this指针——C++学习记录06

1. 深拷贝与浅拷贝

1.1 浅拷贝

编译器提供的简单赋值操作

1.2 深拷贝

程序员在堆区重新空间,进行拷贝操作
问题:在通过Person p2(p1)拷贝构造函数时,编译器将把p1的年age直接赋值给p2,若age是指针变量时,那么p1和p2的age指针都指向了一个存储空间,在析构函数释放对象时,将发生错误。p1和p2都会对一个存储空间进行释放。
运行结果如下:
请添加图片描述

解决办法:通过构造函数来实现深拷贝,即程序员自己通过判断,将指针变量的值开辟到堆区,后将指针变量指向所开辟的空间。那么在析构函数释放空间,将不会存在一个空间被两次释放而引起的问题。

#include<iostream>

using namespace std;

class Person {

public:
    Person() {
        cout << "Person类默认构造函数" << endl;
    }

    Person(int age,int height) {
        cout << "Person有参构造函数" << endl;
        m_Age = age;
        m_Height = new int(height);
    }

    // 实现深拷贝构造函数
    Person(const Person &p) {
        cout << "Person的深拷贝构造函数" << endl;
        m_Age = new int(*p.m_Age);
        
        m_Height = new int(*p.m_Height);
    }

    ~Person() {
        cout << "Person的析构函数调用" << endl;
        if (m_Height != NULL) {
            delete m_Height;
            m_Height = NULL;
        }
        
    }
    int m_Age;
    int* m_Height;
};

void test01() {

    Person p1(18, 178);
    cout << "p1的年龄为" << p1.m_Age << endl;
    cout << "p1的身高为" << *p1.m_Height << endl;

    // 编译器提供的浅拷贝函数
    Person p2(p1);            
    cout << "p2的年龄为" << p2.m_Age << endl;
    cout << "p2的身高为" << *p2.m_Height << endl;


}

int main()
{
    test01();

    system("pause");        
    return 0;
}

2. this指针

2.1 概述

C++中的成员变量和成员函数是分开存储的,每一非静态成员函数只会诞生一份函数实例,多个同类型的对象共用一块代码
C++通过提供特殊的对象指针——this指针来指向被调用的成员函数所属的对象。
this指针是一个隐藏每一个非静态成员函数内的指针,且不需要定义。

2.2 作用

当形参的成员变量同名时,可用this指针来区分。
在类的非静态成员函数中返回对象本省,可用return *this来实现
成员变量weight与形式参数weight同名时,出现的错误:
请添加图片描述

#include<iostream>

using namespace std;
// this指针解决成员变量与形式参数同名的问题
class Dog {
public:
    Dog(int weight) {
        this->weight = weight;            // 解决成员变量与形式参数同名引起的冲突
    }
    int weight;


    Dog dogAddWeight(Dog &d) {            // 返回本身的引用
        this->weight += d.weight;
        return *this;
    }

};


void test02() {

    Dog dog(20);
    cout << "dog的体重为" << dog.weight << endl;

}

void test03() {
    Dog dog01(10);
    Dog dog02(15);
    // 这里dogAddweight()方法实现了返回本身,可以实现多次调用
    // 实现链式编程的思想
    dog02.dogAddWeight(dog01).dogAddWeight(dog01);
    cout << "dog02的体重为" << dog02.weight << endl;
}

int main()
{

    // test02();
    test03();
    system("pause");        
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值