C++ —— 拷贝构造函数(补充)

C++ —— 拷贝构造函数(补充)

#include <iostream>
#include <cstring>
using namespace std;

class Car{
public:
    string c_brand;
    float c_acceleration;
    int* c_ptr; // 添加的指针成员变量

    Car() {
        c_brand.clear();
        c_acceleration = 0.0;
        c_ptr = nullptr; // 初始化指针为空
        cout << "Car constructor" << endl;
    }

    Car(const Car &c) {// 拷贝构造函数
        c_brand = c.c_brand;
        c_acceleration = c.c_acceleration;
        c_ptr = new int; // 分配内存
        // *c_ptr = *(c.c_ptr); // 拷贝数据
        memcpy(c_ptr, c.c_ptr, sizeof(int));
        cout << "Car copy constructor" << endl;
    }

    ~Car() {
        delete c_ptr; c_ptr = nullptr;
        cout << "Car destructor" << endl;
    }

    void show() {cout << "Brand: " << c_brand 
                      << ", Acceleration: " << c_acceleration 
                      << ", c_ptr: " << c_ptr 
                      << ", *c_ptr: " << *c_ptr << endl;
    }
};

int main() {
    Car c1;
    c1.c_brand = "AUDI";
    c1.c_acceleration = 5.0;
    c1.c_ptr = new int(66);
    c1.show();
    Car c2(c1);
    *c2.c_ptr = 888;
    c2.show();
    c1.show();
    
    return 0;
}

运行结果如下:

Car constructor
Brand: AUDI, Acceleration: 5, c_ptr: 0x563396dacec0, *c_ptr: 66
Car copy constructor
Brand: AUDI, Acceleration: 5, c_ptr: 0x563396dacee0, *c_ptr: 888
Brand: AUDI, Acceleration: 5, c_ptr: 0x563396dacec0, *c_ptr: 66
Car destructor
Car destructor

说明

  • 参数:const Car& cc,确保在拷贝过程中不修改被拷贝对象;
  • c_brandc_acceleration从原对象c复制过来;
  • c_ptr分配新的内存new int),并用memcpy()将原对象cc_ptr指向的内存中的数据复制到分配的内存中。实现了所谓的“深拷贝”,保证每个对象管理着自己独立内存资源。

补充内容
C++ —— memset、memcpy、std::copy函数

C++ —— 拷贝构造函数

感谢浏览

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值