c++初学者的随笔记录_4

对象:
1.创建对象的方法:
Human h1;--->>第一种
Human *h2 = new Human();----->>第二种
2.创建默认构造函数:
class Human{
Human();
}
在外面构造
Human::Human(){
.......
}
3.可以在默认的构函数上添加参数来构造有参的构造函数
4.深拷贝:
当类中有需要开辟内存的时候要深拷贝(数组)
char *data;
data = new char[length + 1]; // 分配新内存
strcpy(data, other.data); // 复制内容
===========================================深拷贝
5.赋值构造函数:
class Human {
private:
std::string name;
int age;

public:
// 拷贝赋值运算符声明
Human& operator=(const Human &other);
};

// 拷贝赋值运算符定义
Human& Human::operator=(const Human &other) {
if (this != &other) { // 防止自赋值
name = other.name;
age = other.age;
}
return *this; // 返回当前对象的引用
}
6.关于析构函数的补充:
1.如果在一个class类中定义了一个其他class类,如:computer中定义了cpu---->Cpu cpu他是这样定义的话,系统会自动调用析构来释放内存
2.如果是Cpu *cpu = new Cpu(...);这样定义的话则要在主class(computer)类的析构函数来delete释放内存

posted @ 2025-11-14 14:39  应用宝  阅读(3)  评论(0)    收藏  举报