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_brand和c_acceleration从原对象c复制过来; - 为
c_ptr分配新的内存(new int),并用memcpy()将原对象c的c_ptr指向的内存中的数据复制到新分配的内存中。实现了所谓的“深拷贝”,保证每个对象管理着自己独立的内存资源。
补充内容
C++ —— memset、memcpy、std::copy函数
感谢浏览
&spm=1001.2101.3001.5002&articleId=146180400&d=1&t=3&u=47318ee1133c4798b2ecc2e857b2f7fa)
181

被折叠的 条评论
为什么被折叠?



